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!