Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 520
Johan Kotlinski Avatar asked Jan 28 '11 13:01

Johan Kotlinski


People also ask

Can a class have no data members?

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.

How do you check if a class is empty in C++?

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.

How do you know if a struct is initialized?

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.


2 Answers

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).

like image 185
Konrad Rudolph Avatar answered Oct 05 '22 11:10

Konrad Rudolph


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 class B for which is_empty<B>::value is false.

I don't think there's a standard way to find if a class is empty with regards to polymorphism.

like image 22
GManNickG Avatar answered Oct 05 '22 11:10

GManNickG