Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Type trait to identify primary base class

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<Base*>(derived) is guaranteed (by the Itanium ABI) to be zero, even though Derived is not standard layout. However in the general case this is not necessarily true (eg. multiple inheritance).

Is it possible to write a trait which can be used to detect if one class is the primary base class of another?

Useful sections from the Itanium ABI:

http://refspecs.linux-foundation.org/cxxabi-1.83.html

Primary base class

For a dynamic class, the unique base class (if any) with which it shares the virtual pointer at offset 0. It is the first (in direct base class order) non-virtual dynamic base class, if one exists.

Dynamic class

A class requiring a virtual table pointer (because it or its bases have one or more virtual member functions or virtual base classes).

like image 498
jleahy Avatar asked Feb 28 '13 19:02

jleahy


1 Answers

This will be part of the next standard This was part of the aborted TR2 via the std::bases and std::direct_bases traits. If you happen to be working with a compiler that includes the draft-TR2, you might have support for this. For example in GCC 4.7.2:

#include <demangle.hpp>
#include <iostream>
#include <tr2/type_traits>

struct T1 { };
struct T2 { };
struct Foo : T1, T2 { };


int main()
{
    std::cout << demangle<std::tr2::direct_bases<Foo>::type>() << std::endl;
}

This prints:

std::tr2::__reflection_typelist<T1, T2>

(The demangler is my own; you may have seen it elsewhere.)

I trust you can build a suitable "is polymorphic and has precisely zero or one bases" trait yourself.

like image 142
Kerrek SB Avatar answered Sep 28 '22 22:09

Kerrek SB