1

I have created an ordinary class with a templated method, and all the method instances are explicit and inlined.

Like

class MyClass
{
    template<int N> inline void MyMethod();
    template<> inline void MyMethod<1>() { cout << 1; }
    template<> inline void MyMethod<2>() { cout << 2; }
};

I needed to use the template<> syntax to have it compile. I tried other solutions, such as the explicit definition of the method outside the class declaration, with syntax variants, to no avail. (This was made under VS2008, not tried on later versions.)

I have two questions:

  • is this portable ?
  • does it make sense ?

2 Answers2

2

The way you wrote it is wrong and it won't work.
Member method specializations must be put out of your class:

class MyClass
{
    template<int N> void MyMethod();
};

template<> void MyClass::MyMethod<1>() {  }
template<> void MyClass::MyMethod<2>() { }

It's portable and if it makes sense mostly depends on your actual problem, it's hard to say from your example.

skypjack
  • 49,335
  • 19
  • 95
  • 187
  • it's worth noting that one can move the implementation of such template methods' specializations (as long as header contains appropriate declaration of these specialization) to the source file. While it cannot be done with an unspecialised method template... – W.F. Oct 01 '16 at 09:47
  • @YvesDaoust Actually it [doesn't](https://godbolt.org/g/yEBYVo) [work](https://godbolt.org/g/GzWrlo). Maybe an extension of your compiler? – skypjack Oct 01 '16 at 13:03
  • Sorry, I didn't mention inlining. Fixing. –  Oct 01 '16 at 13:15
  • @YvesDaoust [It doesn't change](https://godbolt.org/g/HMXwpk) the fact that it isn't allowed. – skypjack Oct 01 '16 at 13:19
1

You can't fully specialize member template in class body. Partial specialization are allowed though. Full specializations must be declared/defined outside class body (and definitions should be placed in cpp file if not declared inline).

For reference, this question.

Community
  • 1
  • 1
xinaiz
  • 7,744
  • 6
  • 34
  • 78
  • And as one cannot partially specialize method (it is syntactically forbidden) - one cannot define any method specialization inside the class... However I'm not sure if it is strictly required that the definitions should be in source file I think it's rather an option, while it isn't an option for the unspecialised method template... – W.F. Oct 01 '16 at 11:05
  • Very sorry, I didn't mention inlining –  Oct 01 '16 at 13:15