C ++模板专业化和子类化 [英] C++ Template Specialization and Subclassing

查看:52
本文介绍了C ++模板专业化和子类化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道模板专门化是否可以接受一个类及其子类.像这样:

I was wondering if it is possible to have a template specialization accept a class and its subclasses. Like so:

class A {};

class B : public A {};

template <typename T>
void foo(const T& t) {
  printf("T");
}

template <>
void foo(const A& t) {
  printf("A");
}

int main(int argc, char** argv) {
  B b;
  foo(b);

  return 0;
}

当前它输出'T',因为b没有自己的模板特化,因此它默认打印为'T'.我想知道B是否可以使用A的模板特化功能,因为BA的子类.还是那不是一回事?

Currently it output 'T' because b doesn't have its own template specialization, so it defaults to printing 'T'. I was wondering if it was possible for B to use the template specialization of A since B is a subclass of A. Or is that just not a thing?

注意:由于 some 的要求,我无法使用复制/移动.

Note: Because of some requirement, I can't use copy/move.

注意:如果我不需要更改AB,但我先看看有什么可能,我也希望这样做.

Note: I would also prefer if I didn't need to change A or B, but lets see what is possible first.

推荐答案

探针是,当将T推导为B时,主模板是完全匹配的;比专业化更好.

The probelm is, the primary template is an exact match when T being deduced as B; it's a better match than the specialization.

您可以改用模板重载;与 SFINAE .

You can use template overloading instead; with SFINAE.

template <typename T>
std::enable_if_t<!std::is_base_of_v<A, T>> foo(const T& t) {
  printf("T");
}

template <typename T>
std::enable_if_t<std::is_base_of_v<A, T>> foo(const T& t) {
  printf("A");
}

实时

这篇关于C ++模板专业化和子类化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆