views:

56

answers:

1

I found that template method could be overloaded, can I do the same on template classes? If 2 template classes match a template class instantiation, we can use the parameter type in the constructor to deduce which one to use.

template <typename T>
class A{
  A(T){}
};

template <typename T>
class A{
  A(T*){}
};

int main(){
  A<int*> a((int*)0);
  A<int> a((int*)0);
  return 0;
}
+5  A: 

No. This is not allowed. Instead class template can be specialized (including partial specialization). This pretty much achieves the effect of overloading (which is only for functions)

Note that template parameters can not be deduced from constructor arguments.

template<class T> struct X{
   void f(){}
};

template<class T> struct X<T*>{
   void f(){}
};

int main(){
   X<int> x;
   x.f();          // calls X<T>::f

   X<int *> xs;
   xs.f();         // calls X<T*>::f
}
Chubsdad