C ++ 11:整数类型的模板函数专门化 [英] C++11: Template Function Specialization for Integer Types
本文介绍了C ++ 11:整数类型的模板函数专门化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
假设我有一个模板函数:
Suppose I have a template function:
template<typename T>
void f(T t)
{
...
}
b $ b
并且我想为所有的原始整数类型写一个专门化。这是最好的方法是什么?
and I want to write a specialization for all primitive integer types. What is the best way to do this?
我的意思是:
template<typename I where is_integral<I>::value is true>
void f(I i)
{
...
}
b $ b
并且编译器为整数类型选择第二个版本,而对于所有其他类型选择第一个版本?
and the compiler selects the second version for integer types, and the first version for everything else?
推荐答案
使用 SFINAE
// For all types except integral types:
template<typename T>
typename std::enable_if<!std::is_integral<T>::value>::type f(T t)
{
// ...
}
// For integral types only:
template<typename T>
typename std::enable_if<std::is_integral<T>::value>::type f(T t)
{
// ...
}
请注意,您必须包含完整的 std :: enable_if
甚至为声明返回值。
Note that you will have to include the full std::enable_if
return value even for the declaration.
这篇关于C ++ 11:整数类型的模板函数专门化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文