我有一个单一的继承类层次结构,定义如下:
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
最接近类的共同父类 Ch
和 Co
.例如,调用 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();
}
关于c++ - 如何在类层次结构中找到两个类的共同父类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38853899/