3

I'm basically trying to do what was discussed in Template specialization of a single method from a templated class except that my TClass has multiple template Parameters like this:

template < class KEY, class TYPE >
class TClass
{
public:
    :
    void doSomething(KEY * v);
    :
};

template < class KEY, class TYPE >
void TClass<KEY, TYPE>::doSomething(KEY * v) 
{
    // do something
}

This works so far, but how do I define a specialized implementation for one template Parameter? I tried adding this:

template < class TYPE >
void TClass<int, TYPE>::doSomething(int * v)
{
    // do something if KEY is int
}

but the Compiler complains about "unable to match function Definition to an existing declaration" (VC2010) for that method/function.

As a sidenote: If I specialize both template Parameters at the same time, it works:

template < >
void TClass<int, char>::doSomething(int * v)
{
    // do something if KEY is int and TYPE is char
}

but that's not what I want to do.

Any suggestions?

Community
  • 1
  • 1
marc40000
  • 3,167
  • 9
  • 41
  • 63
  • Btw, the error messages from VS2015 can be wildly unhelpful. C3860: wrong template parameter order, and C2995: template already defined. – Mark Storer Apr 12 '17 at 19:43

2 Answers2

6

You have to specialize the entire class before you define a method through a partial specialization:

template <typename T, typename U>
class TClass;

template <typename T>
class TClass<int, T>
{
    void doSomething(int* v);
};

template <typename T>
void TClass<int, T>::doSomething(int* v)
{
    // ...
}

Live demo

David G
  • 94,763
  • 41
  • 167
  • 253
1

You can fully specialize class method but as far as I remember you can't partially specialize it.

You can try partial specialization for the whole class but this will probably involve a lot of duplication.

Tomek
  • 4,554
  • 1
  • 19
  • 19
  • Both of your answers baasically state the same. I marked 0x499602D2's answer because it is more elaborate. – marc40000 May 27 '13 at 23:08