如何在类层次结构中找到两个类的共同父类
How to find the common parent of two classes in a class hierarchy
我有一个定义如下的单一继承类层次结构:
struct A { using Parent = void; void fnct() { std::cout << "An"; } };
struct AA : A { using Parent = A; void fnct() { std::cout << "AAn"; } };
struct AB : A { using Parent = A; void fnct() { std::cout << "ABn"; } };
struct AAA : AA { using Parent = AA; void fnct() { std::cout << "AAAn"; } };
struct AAB : AA { using Parent = AA; void fnct() { std::cout << "AABn"; } };
struct ABA : AB { using Parent = AB; void fnct() { std::cout << "ABAn"; } };
struct ABB : AB { using Parent = AB; void fnct() { std::cout << "ABBn"; } };
层次结构中的每个类定义了它的直接父类的别名Parent
和成员函数void fnct()
。
我需要定义一个模板函数call_fnct_upto_parent<P,C>(C&)
,对于类C
的给定对象和类层次结构的给定父类P
,调用从对象类型C
到父类型P
的所有成员函数fnct()
。我使用SFINAE实现这一点,如下所示:
template<class P, class C>
typename std::enable_if<!std::is_same<P,C>::value,void>::type call_fnct_upto_parent(C& c)
{
c.fnct();
static_assert(!std::is_same<typename C::Parent,void>::value, "parent not found");
call_fnct_upto_parent<P, typename C::Parent>(c);
}
template<class P, class C>
typename std::enable_if<std::is_same<P,C>::value,void>::type call_fnct_upto_parent(C& c)
{
c.fnct();
}
只要P
是C
的父节点,上面定义的call_fnct_upto_parent<P,C>(C&)
函数就可以正常工作。例如,对call_fnct_upto_parent<A>(aaa)
的调用,其中aaa
的类型为AAA
,会导致后续对aaa.AAA::fnct()
、aaa.AA::fnct()
和aaa.A::fnct()
的调用,这些调用在编译时解析。
现在,我想定义一个模板函数call_fnct_upto_common_parent<Ch,Co>(Co&)
,对于类Co
的给定对象和类层次结构的给定类Ch
,调用从对象类型Co
到类Ch
和Co
最接近的共同父类的类型P
的所有成员函数fnct()
。例如,对call_fnct_upto_common_parent<AB>(aaa)
的调用将导致对aaa.AAA::fnct()
, aaa.AA::fnct()
和aaa.A::fnct()
的后续调用,因为A
类是AB
和AAA
类最接近的共同父类。
这样的函数可以实现吗?如何实现?如果可行,最好使用在编译时解析调用的解决方案。
您可以使用std::is_base_of
与您现有的代码具有类似的结构:
template<class T, class U>
typename std::enable_if<!std::is_base_of<U,T>::value,void>::type
call_fnct_upto_common_parent(U& u)
{
u.fnct();
static_assert(!std::is_same<typename U::Parent,void>::value, "parent not found");
call_fnct_upto_common_parent<T, typename U::Parent>(u);
}
template<class T, class U>
typename std::enable_if<std::is_base_of<U,T>::value,void>::type
call_fnct_upto_common_parent(U& u)
{
u.fnct();
}
相关文章:
- 你好。。。id_public变量不应该给出结果为 81 和 86 吗?为什么它为两个派生类占用不同的内存位置?
- 如何允许模板参数中的类类型,仅当它有两个基类时
- 两个父类的构造函数的序列
- 两个抽象类,派生自同一个基类.如何访问从一个抽象类到另一个抽象类的指针
- 两个继承类如何调用彼此的方法?
- 两个模板类,其中的方法相互调用
- 在两个派生类之间执行专用代码
- 两个模板类相互使用作为模板参数
- 在没有额外代码的情况下链接两个独立类的最通用方法是什么?
- 为什么从两个空类派生的空类的大小是 2?
- 如何在C++中正确表达具有相同实现的两个派生类函数?
- 两个派生类(十六进制 二进制)的虚拟功能
- 具有相同纯虚拟功能的两个基类
- 在两个类似类之间使用reinterpret_cast时错误
- 在方法中返回彼此类型的两个派生类
- 模板化成员函数能否实现两个基类的虚函数?
- C++两个派生类的副本
- 如何使用SWIG中的相同接口生成两个代理类
- 将两个相关类中的数据写入文件
- C++Cycling包括(三个类,两个虚拟类)