Can C++;模板提供N个给定类的公共父类? 我正在寻找一个C++模板,它找到一组给定类的公共父类。

Can C++;模板提供N个给定类的公共父类? 我正在寻找一个C++模板,它找到一组给定类的公共父类。,c++,template-meta-programming,C++,Template Meta Programming,比如说 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

比如说

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();
类动物{…};
哺乳类:公共动物{…};
鱼类类:公共动物{…};
猫类:公共哺乳动物{…};
犬类:公共哺乳动物{…};
std::unique_ptr a=新Cat();
std::unique_ptr b=新狗();
std::unique_ptr c=new Fish();//编译错误
std::unique_ptr d=新鱼();
a
b
都是
std::unique_ptr
c
std::unique_ptr


这是如何与现代C++(?)/< > P > AFAIK不,C++中没有方法获得给定类的基类。作品中有内省(反思的一部分),但我不会屏住呼吸让它很快进入标准


唯一的办法是让班级合作。例如,使用Base=Animal让每个a类成员别名
。然后烹调一种特质,找出它们之间的共同基础。那将是一个很大的工作。您需要考虑多个基类和继承链。这不是小事。你需要分析你的问题,看看所有这些复杂的工作是否值得,或者是否有其他更简单的方法来实现你的目标(顺便说一句,你没有提到)。您可能有问题。

否,
的公共祖先需要反射才能获取任何给定类的基类

如果您有一组具体的类,那么可以使用所有可能的类的
std::variant

如果不是,您可以使用基类特征(您专门用于所有类型的struct
base\u class
,或者像使用super=…或
使用base=…
这样的成员类型)并手动查找公共祖先:

模板
结构类型标识{
使用类型=T;
};
模板
结构的公共祖先;
模板
结构的公共祖先{
使用类型=T;
};
模板
结构的公共祖先{
使用类型=T;
};
模板
结构公共祖先:公共祖先{};
模板
结构的公共祖先{
私人:
//Base==派生的,所以在它的继承链中
模板
继承链中的静态constexpr布尔(int){
返回true;
}
//Base!=派生,但派生的成员类型为'super',因此递归检查'super'`
模板{},true),int>::type=0>
继承链中的静态constexpr布尔(int){
_继承_链中的返回(0);
}
//Base!=派生和派生没有成员类型“super”,因此它不在继承链中
模板
继承链中的静态constexpr布尔(长){
返回false;
}
//T1位于U1的继承链中,因此它是共同的祖先
模板
静态类型标识查找公共祖先(int);
//T1不在继承链中,因此请检查T1::super
模板
静态decltype(find_common_祖先(0))find_common_祖先(long){
公众:
使用type=typename decltype(查找公共祖先(0))::type;
};
模板
使用common\u祖先\u of_t=typename common\u祖先\u of::type;
动物类{};
哺乳动物类:公共动物{public:using super=Animal;};
鱼类类:公共动物{public:using super=Animal;};
类别Cat:公共哺乳动物{public:使用super=哺乳动物;};
狗类:公共哺乳动物{public:using super=哺乳动物;};
静态断言(std::is\u same::value);
静态断言(std::is\u same::value);
静态断言(std::is\u same::value);
静态断言(std::is\u same::value);
静态断言(std::is\u same::value);

这是最专业化的共同祖先,但是考虑使用你已经拥有的共同祖先:<代码> STD::UnQuyJPPT。如果您在代码中专门编写

std::unique\ptr
,那么编写
std::unique\ptr
同样容易。如果它在一些模板代码后面,
std::unique_ptr
也应该可以工作。

是的…………也许-@JHBonarius如何?我不知道有什么方法可以找到它。@RichardCritten否,
std::common_type
不能用于查找基类。否,这是不可能的。如果不将信息存储在元函数的某个地方,就无法从typename Y中变出typename X。对于继承链中
false
重载,
false
?@JHBonarius作为参数传递的
0
int
,但也匹配
long
,因此只有在无法匹配任何
int
重载时才会调用
long
重载。这使我无法编写一个具有超级
特征的