Question

Say I declared a class with a template method.

class MyClass {
    ...
    template<typename T> void myMethod(const T& obj);
}

I have defined a generic version of the method

template<typename T>
void MyClass::myMethod(const T& obj) { .... }

and want to define several specializations for various types. What is the correct syntax? VS2013 compiler does not seem to approve my attempts.

template<>
void MyClass::myMethod<int>(const int &) {....}

or

template<int>
void MyClass::myMethod(const int &) { .... }
Was it helpful?

Solution

The first syntax is ok, as a specialization. The second is wrong as it is defining a template<int> while myMethod is declared as a template<typename>. But keep in mind that a specialization isn't needed at all, an overload is just fine, like

class MyClass {
   void myMethod(const int& obj) { ... }
   // ... more overloads
};

Of course, if you need to separate declarations from definitions (which I avoid for templates), this leads to more code duplication. Depending on type, this way you may also enforce call by value, e.g.

void myMethod(bool obj) { ... }

which does not apply to your specializations.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top