明确的模板专业化问题

bjs*_*123 3 c++

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.
}
Run Code Online (Sandbox Code Playgroud)

链接器错误是

error LNK2019: unresolved external symbol "public: void __thiscall
Test<int>::f<char>(void)"
Run Code Online (Sandbox Code Playgroud)

我的要求是:我应该能够将任何类型传递给Test类,并将任何类型传递给函数f().我应该可以使用下面所有类型的组合.

  Test   f()
  --------------
  int    char
  char   int
  int    int
Run Code Online (Sandbox Code Playgroud)

我可以通过定义下面的另一个函数来解决错误.

template<>
template<> void Test<int>::f<char>(){}
Run Code Online (Sandbox Code Playgroud)

但是,将Test类作为模板的用途是什么?如何让它适用于所有组合?

vit*_*aut 5

C++ 03,§14.7.3/ 2:

应在模板所属的名称空间中声明显式特化,或者对于成员模板,在封闭类或封闭类模板所属的名称空间中声明.应该在类模板所属的名称空间中声明类模板的成员函数,成员类或静态数据成员的显式特化.

因此,您应该在类之外声明您的专业化,例如:

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>();
}
Run Code Online (Sandbox Code Playgroud)