I want to specialize specific function in template class.
Eg:
template<class T>
class A
{
public :
void fun1(T val);
void fun2(T val1, T val2);
};
template <class T>
void A<T>::fun1(T val)
{
// some task 1;
}
template <class T>
void A<T>::fun2(T val1, T val2)
{
// some task 2;
}
template <>
void A<char*>::fun2(char* val1, char* val2)
{
// some task 2 specific to char*;
}
when I do something like this, I get error saying multiple definition for fun2()
Please let me why this wrong and also the correct way to implement this.
Your method
fun2()is not atemplatemethod as itself, though it’s a member of atemplateclass. I don’t find the proper technical term but in simple words, specializingfun2()will create an effect of a normal function definition. Putting the definition in header file will give you multiple definition error.To solve this problem, just put an
inlinekeyword and the linker error will go away!Edit: This solves the linker error. But still you cannot use the
A<char*>::fun2. Ultimately it boils down to the very fact that you need to specialize the wholeclass A<char*>or overload thefun2(char*, char*)withinA<T>