문제

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 &) { .... }
도움이 되었습니까?

해결책

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.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top