c++ - 如何在类层次结构中找到两个类的共同父类

标签 c++ inheritance parent-child sfinae

我有一个单一的继承类层次结构,定义如下:

struct A        { using Parent = void;  void fnct() { std::cout << "A\n";   } };
struct AA : A   { using Parent = A;     void fnct() { std::cout << "AA\n";  } };
struct AB : A   { using Parent = A;     void fnct() { std::cout << "AB\n";  } };
struct AAA : AA { using Parent = AA;    void fnct() { std::cout << "AAA\n"; } };
struct AAB : AA { using Parent = AA;    void fnct() { std::cout << "AAB\n"; } };
struct ABA : AB { using Parent = AB;    void fnct() { std::cout << "ABA\n"; } };
struct ABB : AB { using Parent = AB;    void fnct() { std::cout << "ABB\n"; } };

层次结构中的每个类定义一个别名Parent到它的直接父类,以及一个成员函数void fnct() .

我需要定义一个模板函数 call_fnct_upto_parent<P,C>(C&)其中,对于类的给定对象 C和给定的父类 P在类层次结构中,调用所有成员函数 fnct()来自对象类型 C直到父类型 P .我使用 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();
}

函数call_fnct_upto_parent<P,C>(C&)只要P,上面定义的就可以正常工作是 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在类层次结构中,调用所有成员函数 fnct()来自对象类型 Co直至类型 P最接近类的共同父类 ChCo .例如,调用 call_fnct_upto_common_parent<AB>(aaa) , 将导致后续调用 aaa.AAA::fnct() , aaa.AA::fnct()aaa.A::fnct() , 因为类 A是最接近类的共同父类 ABAAA .

能否实现这样的功能,如何实现?如果可行,在编译时解决调用的解决方案将是更可取的。

感谢您的帮助。

最佳答案

您可以使用具有与现有代码类似结构的 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();
}

关于c++ - 如何在类层次结构中找到两个类的共同父类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38853899/

相关文章:

c++ - 与迭代相比,为什么我的二进制搜索如此慢?

c++ - MSVC 2010 : Allow right-click menu in console during input

c++ - 候选函数不可行:没有已知的从 std::vector 到 std::vector 的转换

c++ - C++ 中的继承 : define variables in parent-child classes

Maven:不可解析的父 POM

C++ 模块 "failed to read module ' std.io.gcm' : No such file or directory"

c++ - 如何以编程方式启动 Windows 应用商店应用程序?

c++ - 继承和存储静态类信息

java - 继承方法返回引用类型

javascript - 选择相邻元素的子元素