开发者

Is it possible to overload a template class?

开发者 https://www.devze.com 2023-01-22 17:22 出处:网络
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

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开发者_StackOverflow社区(){
  A<int*> a((int*)0);
  A<int> a((int*)0);
  return 0;
}


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
}
0

精彩评论

暂无评论...
验证码 换一张
取 消