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.
If your compiler supports this aspect of C++0x, you can use
std::is_empty
from<type_traits>
.It's specification is:
I don't think there's a standard way to find if a class is empty with regards to polymorphism.
Stepping on Konrad's answer, this handles classes with or without virtual functions.
The most simple answer to this that both works and is standard complaint: Look at the header files for the class/struct and its class hierarchy. They will tell you if there are data elements (as well as a vtable).
Since C++11, you can use standard
std::is_empty
trait: https://en.cppreference.com/w/cpp/types/is_emptyIf you are on paleo-compiler diet, there is a trick: you can derive from this class in another empty and check whether
sizeof(OtherClass) == 1
. Boost does this in itsis_empty
type trait.Untested:
However, this relies on the empty base class optimization (but all modern compilers do this).