zoukankan      html  css  js  c++  java
  • c++11函数模板“偏特化”的一种实现

    c++11模板的偏特化仅限于类模板,对于函数模板的偏特化,就需要借助std::enable_if类自动去编译enbale通过的函数。

    问题描述:实现一个插值模板,把光滑阶数作为模板参数,实现1阶光滑的插值和2阶连续的插值。

    template<typename type, unsigned int smoothness = 1>
    typename enable_if<smoothness == 1, type>::type
    interpolate(const type& a, const type& b, const type& x){
        return x < a ? 0 : (x > b ? 1 : (x - a) / (b - a));
    }
    
    template<typename type, unsigned int smoothness>
    typename enable_if<smoothness == 2, type>::type
    interpolate(const type& a, const type& b, const type& x){
        auto y = (x - a) / (b - a);
        return y < 0 ? 0 : (y > 1 ? 1 : y * y * (static_cast<type>(3) - static_cast<type>(2) * y));
    }

    另一种应用是函数需要对整型和浮点型有不同的实现方式,也可以使用std::enable_if 和 类型判别模板is_floating_point和is_integral实现。

    template<typename type>
    typename std::enable_if<std::is_floating_point<type>::value, void>::type
    print(const type& value){
        cout<<"floating:"<<value<<endl;
    }
    
    
    template<typename type>
    typename std::enable_if<std::is_integral<type>::value, void>::type
    print(const type& value){
        cout<<"integral:"<<value<<endl;
    }
  • 相关阅读:
    【蓝桥杯训练】第二天1261
    【蓝桥杯训练】第二天1259、1260
    【蓝桥杯训练】第二天1255、1258
    【蓝桥杯训练】第一天1252
    【蓝桥杯训练】第一天1253
    【蓝桥杯训练】第一天1251
    【蓝桥杯训练】第一天1250
    Map,reduce,zip,dir 简化你的操作
    C# await和async
    python 入门笔记
  • 原文地址:https://www.cnblogs.com/wkcagd/p/14375878.html
Copyright © 2011-2022 走看看