pep*_*er0 12 c++ templates specialization
假设我们有一个模板函数"foo":
template<class T>
void foo(T arg)
{ ... }
Run Code Online (Sandbox Code Playgroud)
我可以针对某些特定类型进行专业化,例如
template<>
void foo(int arg)
{ ... }
Run Code Online (Sandbox Code Playgroud)
如果我想对所有内置数值类型(int,float,double等)使用相同的特化,我会多次写这些行.我知道身体可以被扔到另一个功能,并且只是在每个专业的身体中调用它,但是如果我能避免为每种类型写出这个"void foo(...")会更好.是否有有没有可能告诉编译器我想对所有这些类型使用这个特化?
Joh*_*itb 19
您可以使用std::numeric_limits查看类型是否为数字类型(is_specialized对于所有浮点和整数基本类型都是如此).
// small utility
template<bool> struct bool2type { };
// numeric
template<typename T>
void fooImpl(T arg, bool2type<true>) {
}
// not numeric
template<typename T>
void fooImpl(T arg, bool2type<false>) {
}
template<class T>
void foo(T arg)
{ fooImpl(arg, bool2type<std::numeric_limits<T>::is_specialized>()); }
Run Code Online (Sandbox Code Playgroud)