Explicit template specialization problem

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.
}

Linker Error

error LNK2019: unresolved external symbol "public: void __thiscall
Test<int>::f<char>(void)"

My requirement: I should be able to pass any type of Test to a class and any type of f () function. I should be able to use all type combinations as shown below.

  Test   f()
  --------------
  int    char
  char   int
  int    int

I can solve this error by specifying another function as shown below.

template<>
template<> void Test<int>::f<char>(){}

But why use the Test class as a template? How to make it work for all combinations?

+3
source share
3 answers

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>();
}
+5

, , , f char Test, . , , f char :

template <typename T>
struct Test {
   template <typename U> void f();
   template <> void f<char>();       // <- Incorrect
};

Test<int>, () , f char Test<int>.

, . Test<char>::f<char>(), , , .

f char , . , . , -:

template <typename T>
struct Test {
   template <typename U> void f( U );
   void f( char );
};

, ( ). , , , , :

int main() {
   Test<int> t;
   t.f<char>(); // will call template, not "void f(char)"!!
}

, , .

+3

: Test f(). , .

? ?

Listed below are all the combinations you listed.

template <class T>
class Test
{
public:
    template<class U> void f(); 
};

template <class T>
template<class U>
void Test<T>::f(){}   

int main()
{
    Test<char> ob1;
    ob1.f<char>(); //Works fine. T = char, U = char

    Test<int> ob2;
    ob2.f<char>();  //Works fine T = int, U = char
}
0
source

Source: https://habr.com/ru/post/1772335/


All Articles