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.
No, because static functions can't be declared as members of parent classes, while data-less member classes can. Thus the constructor of a member-less class in an enclosing class will be called automatically. This feature can'be reached by a static function.
is_empty template in C++ The std::is_empty template of C++ STL is used to check whether the given type is empty or not. This method returns a boolean value showing whether the given type is empty or not.
The only way you could determine if a struct was initialized would be to check each element within it to see if it matched what you considered an initialized value for that element should be.
Since C++11, you can use standard std::is_empty
trait: https://en.cppreference.com/w/cpp/types/is_empty
If 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 its is_empty
type trait.
Untested:
template <typename T>
struct is_empty {
struct helper_ : T { int x; };
static bool const VALUE = sizeof(helper_) == sizeof(int);
};
However, this relies on the empty base class optimization (but all modern compilers do this).
If your compiler supports this aspect of C++0x, you can use std::is_empty
from <type_traits>
.
It's specification is:
T
is a class type, but not a union type, with no non-static data members other than bit-fields of length 0, no virtual member functions, no virtual base classes, and no base classB
for whichis_empty<B>::value
isfalse
.
I don't think there's a standard way to find if a class is empty with regards to polymorphism.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With