Alex Rivera | Logout

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

Asked 2011-01-28T13:57:09.697
19

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.

Edit
Report

1 Answer

3

Stepping on Konrad's answer, this handles classes with or without virtual functions.

template <typename T>
struct is_empty {
    struct empty_ { virtual ~empty_(); };
    struct helper_ : T { virtual ~helper_(); };
    static bool const EMPTY = sizeof(helper_) == sizeof(empty_);
};
answered 2011-01-28T14:36:26.917

Your Answer