c++ - C++ 模板能否提供 N 个给定类的公共(public)父类?

标签 c++ template-meta-programming

我正在寻找一个 C++ 模板,它可以找到一组给定类的共同父类。

例如

class Animal { ... };
class Mammal : public Animal { ... };
class Fish   : public Animal { ... };
class Cat    : public Mammal { ... };
class Dog    : public Mammal { ... };

std::unique_ptr<common_ancestor_of<Cat,Dog>::type> a = new Cat();
std::unique_ptr<common_ancestor_of<Cat,Dog>::type> b = new Dog();
std::unique_ptr<common_ancestor_of<Cat,Dog>::type> c = new Fish(); // compile error
std::unique_ptr<common_ancestor_of<Cat,Dog,Fish>::type> d = new Fish();

ab都是std::unique_ptr<Mammal> , cstd::unique_ptr<Animal> .

这在现代 C++ 中如何实现?

最佳答案

Afaik 不,在 C++ 中没有办法获取给定类的基类。作品中有内省(introspection)(反射(reflection)的一部分),但我不会屏住呼吸让它很快进入标准。

唯一的办法就是让类(class)合作。例如。为每个类设置一个成员别名using Base = Animal。然后烹调一个特征,找到它们之间的共同基础。那将是很多工作。您需要考虑多个基类和继承链。这不是微不足道的。你需要分析你的问题,看看所有这些复杂的工作是否值得,或者是否有另一种更简单的方法来实现你想要实现的目标(顺便说一句,你没有提到)。你可能有一个 XY你手上的问题。

关于c++ - C++ 模板能否提供 N 个给定类的公共(public)父类?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65619415/

相关文章:

c++ - 创建货币数据类型 C++

c++ - 根据表达式的有效性选择要应用的函数

c++ - SFINAE : Detecting if a function is called by a compile time known value

c++ - 传递对象并从线程调用中获取返回值

C++ 指针运行时错误

c++ - Rcpp_模块 : exposing class method with formal R arguments

c++ - 如何检测类型是否可以流式传输到 std::ostream?

c++ - 单元测试高度模板化的库

c++ - 模板模板函数参数

c++ - DebugBreak 不中断