以下は、C ++ 11のみで役立つことを行うための、徹底的にテストされていないワイルドな試みです(実際には、C ++ 11の機能は実際には必要ありませんが、この方法で作成する方が簡単です)。
ただし、この特性は、「isprimarybaseclassof」プロパティの推移閉包のみをチェックします。クラスが別のクラスの直接基本クラスであるかどうかを確認する非侵入的な方法を理解できませんでした。
#include <type_traits>
template<typename B, typename D, D* p = nullptr, typename = void>
struct is_primary_base_of : std::false_type { };
template<typename B, typename D, D* p>
struct is_primary_base_of<B, D, p,
typename std::enable_if<
((int)(p + 1024) - (int)static_cast<B*>(p + 1024)) == 0
>::type
>
:
std::true_type { };
次に例を示します。
struct A { virtual ~A() { } };
struct B : A { };
struct C { virtual ~C() { } };
struct D : B, C { };
struct E : virtual A, C { };
int main()
{
// Does not fire (A is PBC of B, which is PBC of D)
static_assert(is_primary_base_of<A, D>::value, "Error!");
// Does not fire (B is PBC of C)
static_assert(is_primary_base_of<B, D>::value, "Error!");
// Fires (C is not PBC of D)
static_assert(is_primary_base_of<C, D>::value, "Error!");
// Fires (A is inherited virtually by E, so it is not PBC of E)
static_assert(is_primary_base_of<A, E>::value, "Error!");
// Does not fire (C is the first non-virtual base class of E)
static_assert(is_primary_base_of<C, E>::value, "Error!");
}