检测公共基类

时间:2017-05-06 01:51:40

标签: c++ c++11 inheritance introspection base-class

假设一个人有一个类层次结构,没有多重继承:

struct TOP{};
struct L : TOP{}; 
struct R : TOP{};
struct LL : L{};
struct LR : L{};
struct RL : R{};
struct RR : R{};

是否可以编写一个返回两种类型公共基类型的元函数? (如果不存在公共基类,它可以返回void。) 例如

common_base<RR, R>::type == R
common_base<RL, RR>::type == R
common_base<LL, RR>::type == TOP
common_base<LL, std::string>::type == void

显然,这不适用于多个inhertance,但我专注于单继承案例。

首先,如果没有基类的内省,似乎是不可能的。所以,我有这个更容易的问题,以每个clase知道它的基础(通过内部base类型)的方式来做,例如:

struct LR : L{using base = L;};

即便以这种方式,我似乎无法正确地进行元编程。

我也读到了某处(我现在找不到),GCC有一些扩展来检测公共基类。是这样的吗?

2 个答案:

答案 0 :(得分:3)

在std :: tr2 bases中有某些时候but that wasn't includeddirect_bases。某些版本的gcc有它。使用这些也许你可以得到你想要的东西。

答案 1 :(得分:1)

如果您将每个类别作为基数base(如下所示),则可以完成。

struct Child : Parent { using base = Parent; }; //typedef works too

我创建了struct

template <class T1, class T2>
struct CommonBase;

CommonBase的工作原理是将T2的每个基数与T1进行比较。当它到达顶层基础时,它再次从底部开始,但与T1的基础进行比较。

例如:CommonBase<RL, RR>将进行以下检查:

RL !=  RR
RL !=  R
RL !=  Top
R  !=  RR
R  ==  R

所以CommonBase<RL, RR>::type == R。如果没有共同基础,type == void

我把代码放在最后因为模板元编程很漂亮:

#include <type_traits>

template <class T>
struct GetBase //type = T::base, or else void
{
    template <class TT> static typename TT::base& f(int);
    template <class TT> static void f(...);
    typedef std::remove_reference_t<decltype(f<T>(0))> type;
};

template <class T1, class T2>
struct Compare2 //Compares T1 to every base of T2
{
    typedef typename GetBase<T2>::type _type;
    template <class T, bool = !std::is_same<T, void>::value>
    struct helper
    {
        typedef typename Compare2<T1, T>::type type;
    };
    template <class T>
    struct helper<T, false>
    {
        typedef void type;
    };
    typedef typename helper<_type>::type type;
};

template <class T>
struct Compare2<T, T>
{
    typedef T type;
};

template <class T1, class T2>
struct Compare1 //Uses Compare2 against every base of T1
{
    typedef typename GetBase<T1>::type _type;
    template <class T, bool = !std::is_same<T, void>::value>
    struct helper
    {
        typedef typename Compare1<T, T2>::type type;
    };
    template <class T>
    struct helper<T, false>
    {
        typedef void type;
    };
    typedef std::conditional_t<std::is_same<typename Compare2<T1, T2>::type, void>::value, typename helper<_type>::type, typename Compare2<T1, T2>::type> type;
};

template <class T>
struct Compare1<T, T> //Probably redundant
{
    typedef T type;
};

template <class T1, class T2>
struct CommonBase //You can throw a std::enable_if on this to limit it to class types
{
    typedef typename Compare1<T1, T2>::type type;
};

Here您可以在某些测试用例中看到它。