user1196549
user1196549

Reputation:

Explicit class member instantiation

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:

Upvotes: 1

Views: 113

Answers (2)

xinaiz
xinaiz

Reputation: 7788

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.

Upvotes: 1

skypjack
skypjack

Reputation: 50550

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.

Upvotes: 2

Related Questions