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;
}