我正在寻找一个 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();
a
和 b
都是std::unique_ptr<Mammal>
, c
是std::unique_ptr<Animal>
.
这在现代 C++ 中如何实现?
最佳答案
Afaik 不,在 C++ 中没有办法获取给定类的基类。作品中有内省(introspection)(反射(reflection)的一部分),但我不会屏住呼吸让它很快进入标准。
唯一的办法就是让类(class)合作。例如。为每个类设置一个成员别名using Base = Animal
。然后烹调一个特征,找到它们之间的共同基础。那将是很多工作。您需要考虑多个基类和继承链。这不是微不足道的。你需要分析你的问题,看看所有这些复杂的工作是否值得,或者是否有另一种更简单的方法来实现你想要实现的目标(顺便说一句,你没有提到)。你可能有一个 XY你手上的问题。
关于c++ - C++ 模板能否提供 N 个给定类的公共(public)父类?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65619415/