(我假设知道这个问题中的 Abrahams/Dimov example。)
假设标题中有一些 3rd 方代码,您无法修改:
template<class T> void f(T); // (1) base template 1
template<class T> void f(T *); // (2) base template 2
template<> void f<>(int *); // (3) specialization of (2)
问题是:
如果我按原样得到上面的声明,是否有可能我现在可以针对 T = int *
(例如)?
或者仅仅声明基本模板 2 就意味着基本模板 1 不能再专门化(至少对于指针而言)?
最佳答案
您可以通过在函数名称后的尖括号中显式指定模板参数来重载 (1)(参见 C++11-Standard 14.7.3)
#include <iostream>
using namespace std;
template<class T> void f(T) // (1) base template 1
{
cout << "template<class T> void f(T)" << endl;
}
template<class T> void f(T *) // (2) base template 2
{
cout << "template<class T> void f(T *)" << endl;
}
//template<> void f<>(int *); // (3) specialization of (2)
template<> void f<int*>(int *) // (4) specialization of (1)
{
cout << "f<int*>(int *)" << endl;
}
int main() {
int i;
f(&i); // calls (2) since only base-templates take part in overload resolution
return 0;
}
关于c++ - 函数模板特化和 Abrahams/Dimov 示例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14786008/