views:

316

answers:

3

Hello.

Always considering that the following header, containing my templated class, is included in at least two .CPP files, this code compiles correctly:

template <class T>
class TClass 
{
public:
 void doSomething(std::vector<T> * v);
};

template <class T>
void TClass<T>::doSomething(std::vector<T> * v) {
 // Do somtehing with a vector of a generic T
}

template <>
inline void TClass<int>::doSomething(std::vector<int> * v) {
 // Do somtehing with a vector of int's
}

But note the inline in the specialization method. It is required for the code not to have linker error (in VS2008 is LNK2005) due to the method being defined more then once. I understand this because AFAIK a full template specialization is the same as a simple method definition.

So, how do I remove that inline? The code should not be duplicated in every use of it. I've searched Google, read some questions here in SO and tried many of the suggested solutions but none was successfully built (at least not in VS 2008).

Thanks!

+2  A: 

As with simple functions you can use declaration and implementation. Put in your header declaration:

template <>
void TClass<int>::doSomething(std::vector<int> * v);

and put implementation into one of your cpp-files:

template <>
void TClass<int>::doSomething(std::vector<int> * v) {
 // Do somtehing with a vector of int's
}

Don't forget to remove inline (I forgot and thought this solution will not work :) ). Checked on VC++2005

maxim1000
I did tried something at least similar to this before but I got other errors but now that you mentioned I must have forgotten to remove the `inline` while copy/pasting. This way it worked!
Chuim
A: 

You need to move specialization definition to CPP file. Specialization of member function of template class is allowed even if function is not declared as template.

BostonLogan
This was the direction I was already aware of. But I was looking for the final answer because I wasn't getting it right.
Chuim
A: 

There is no reason to remove the keyword inline.
It does not change the meaning of the code in anyway.

Martin York
Copied from the question comment:Because if this method would be "long" and used in many places I would get its binary code copied everywhere, right? I tried to explain this in the question but I guess it wasn't clear... :)
Chuim
No. The linker removes any extra copies. So within an application or lib you would only have once instance of the method.
Martin York