Search code examples
c++classstructsizemember

Is there an easy way to tell if a class/struct has no data members?


Hallo,

is there some easy way in C++ to tell (in compile-time) if a class/struct has no data members?

E.g. struct T{};

My first thought was to compare sizeof(T)==0, but this always seems to be at least 1.

The obvious answer would be to just look at the code, but I would like to switch on this.


Solution

  • Since C++11, you can use the std::is_empty trait.

    If you are on paleo-compiler diet, you can use the Boost.TypeTraits implementation of is_empty. It relies on empty base optimisation, which is performed by all mainstream C++ Compilers, and ensures that an empty base class will take up zero space in a derived class.

    The Boost.TypeTraits implementation uses a helper class which is derived from the class the user wants to test, and which is of a fixed, known size. A rough outline of the logic is as follows:

    template <typename T>
    struct is_empty {
        struct helper : T { int x; };
        static bool const VALUE = sizeof(helper) == sizeof(int);
    };
    

    However, beware that the actual Boost implementation is more complex since it needs to account for virtual functions (all mainstream C++ compilers implement classes with virtual functions by adding an invisible data member for the virtual function table to the class). The above is therefore not sufficient to implement is_empty correctly!