Type trait to identify primary base class

前端 未结 2 2030
迷失自我
迷失自我 2021-01-12 07:02

If I have a class Base, with at least one virtual function, and a class Derived which inherits singly from this then (uintptr_t)derived - (uintptr_t)static_cast

2条回答
  •  深忆病人
    2021-01-12 07:36

    Below is a wild, not thoroughly tested attempt at doing something helpful with C++11 only (actually, it does not really require any C++11 feature, but it's easier to write this way).

    However, this trait only checks the transitive closure of the "is primary base class of" property: I could not figure out a non-intrusive way of verifying whether a class is a direct base class of another class.

    #include 
    
    template
    struct is_primary_base_of : std::false_type { };
    
    template
    struct is_primary_base_of(p + 1024)) == 0
            >::type
        >
        :
        std::true_type { };
    

    Here is an example:

    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::value, "Error!");
    
        // Does not fire (B is PBC of C)
        static_assert(is_primary_base_of::value, "Error!");
    
        // Fires (C is not PBC of D)
        static_assert(is_primary_base_of::value, "Error!");
    
        // Fires (A is inherited virtually by E, so it is not PBC of E)
        static_assert(is_primary_base_of::value, "Error!");
    
        // Does not fire (C is the first non-virtual base class of E)
        static_assert(is_primary_base_of::value, "Error!");
    }
    

提交回复
热议问题