我对函数的显式模板专门化的语法感到有些困惑。
假设我有以下几点:
template<class T>
void f(T t)
{}
我知道对于显式专业化我需要提供template <>
,否则我会超载。以下两个编译:
// (a)
template<>
void f<int>(int t)
{}
//(b)
template<>
void f(int t)
{}
但是,(a)和(b)有什么区别?
如所写,两者都做相同的事情。模板参数推导用于确定T
显式专业化中的类型。当您具有重载功能模板时,将开始“乐趣”:
template<class T> //#1
void f(T t)
{}
template<class T> //#2
void f(T* t)
{}
template<>
void f<int*>(int* t) // specializes #1
{}
template<>
void f(int* t) // specializes #2, equivalent to void f<int>(int* t)
{}
更改订单后,真正的“乐趣”就会开始:
template<class T> //#1
void f(T t)
{}
template<>
void f(int* t) // specializes #1, equivalent to void f<int*>(int* t)
{}
template<class T> //#2
void f(T* t)
{}
在这种情况下,您得到与直觉相反的结果:
int *p;
f(p); // calls #2, not explicitly specialized #1
这就是为什么对函数模板使用重载而不是显式专门化通常更好。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句