是否可以重载模板类?

发布于 2024-09-29 20:44:18 字数 288 浏览 0 评论 0原文

我发现模板方法可以重载,我可以在模板类上做同样的事情吗?如果两个模板类与一个模板类实例化相匹配,我们可以使用构造函数中的参数类型来推断使用哪一个。

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

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

誰認得朕 2024-10-06 20:44:18

不可以,这是不允许的。相反,类模板可以是专门化​​的(包括部分专门化)。这几乎达到了重载的效果(仅适用于函数)。

请注意,模板参数不能从构造函数参数推导出来。

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
}

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
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文