template <class T>
class Test
{
public:
template<class U> void f(); //generic function
template<> void f<char>(); //Specialization for char.
};
template <class T>
template<class U>
void Test<T>::f() //Definition of generic function
{
}
template<>
template<> void Test<char>::f<char>(){} //Definition of specialization.
int main()
{
Test<char> ob1;
ob1.f<char>(); //Works fine.
Test<int> ob2;
ob2.f<char>(); //Produces linker error.
}
链接器错误是
error LNK2019: unresolved external symbol "public: void __thiscall
Test<int>::f<char>(void)"
我的要求是:我应该能够将任何类型传递给测试类,并将任何类型传递给函数 f()。我应该能够使用如下所示的所有类型组合。
Test f() -------------- int char char int int int
我可以通过如下定义另一个函数来解决错误。
template<>
template<> void Test<int>::f<char>(){}
但是,将 Test 类作为 Template 有什么用呢?如何使其适用于所有组合?
最佳答案
C++03,§14.7.3/2:
显式特化应在其命名空间中声明 template 是成员,或者对于成员模板,在其命名空间中 封闭类或封闭类模板是一个成员。 成员函数、成员类或静态数据的显式特化 类模板的成员应在其命名空间中声明 类模板是一个成员。
因此您应该在类之外声明您的特化,例如:
template <class T>
class Test
{
public:
template<class U> void f(); //generic function
};
template <class T>
template <class U>
void Test<T>::f() {} //Definition of generic function
template<>
template<>
void Test<char>::f<char>(){} //Specialization.
int main()
{
Test<char> ob1;
ob1.f<char>();
Test<int> ob2;
ob2.f<char>();
}
关于c++ - 显式模板特化问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4062388/