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;
    }
  • 相关阅读:
    codeforce 272B Dima and Sequence
    Codeforce 270D Greenhouse Effect
    codeforce 270C Magical Boxes
    codeforce 270B Multithreading
    图论--Dijkstra算法总结
    图论--(技巧)超级源点与超级汇点
    图论--Floyd总结
    ZOJ 3932 Handshakes
    ZOJ 3932 Deque and Balls
    ZOJ 3927 Programming Ability Test
  • 原文地址:https://www.cnblogs.com/wkcagd/p/14375878.html
Copyright © 2011-2022 走看看