Template class with a single method specialized in C ++

I only have the hpp file for the school assignment in C ++ (I am not allowed to add the cpp file, the declaration and implementation must be written to the file).

I wrote this code inside it:

template<class T> class Matrix { void foo() { //do something for a T variable. } }; 

I would like to add another foo method, but this foo() will be specialized only for <int> . I read in some places that I need to declare a new specialization class for this. But I want the specialized foo lie only under the original foo , so it will look like this:

 template<class T> class Matrix { void foo(T x) { //do something for a T variable. } template<> void foo<int>(int x) { //do something for an int variable. } }; 
  • Why am I getting an error for this syntax ("expected unqualified identifier before" and "token")?
  • Why is this impossible?
  • How can I fix this without declaring a new specialized class?

thanks

+6
source share
2 answers

foo not a template. This is a member function of a template. So foo<int> doesn't make sense. (In addition, explicit specializations must be declared in the namespace area.)

You can explicitly specialize a member function of a specific implicit instance of a class template:

 template<class T> class Matrix { void foo(T x) { //do something for a T variable. } }; // must mark this inline to avoid ODR violations // when it defined in a header template<> inline void Matrix<int>::foo(int x) { //do something for an int variable. } 
+10
source

You need to define the original foo method as a template, and in fact there is no need for your class to be a template, only the method:

 class Matrix { template<typename T> void foo(T x) { //do something for a T variable. } template<> void foo<int>(int x) { //do something for an int variable. } }; 

UPDATE: code works only in Visual Studio. Here is code that should work elsewhere:

 class Matrix { template<typename T> void foo(T x) { //do something for a T variable. } }; template<> void Matrix::foo<int>(int x) { //do something for an int variable. } 
0
source

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


All Articles