开发者

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开发者_如何学C obvious answer would be to just look at the code, but I would like to switch on this.


Since C++11, you can use the std::is_empty trait.

If you are on paleo-compiler diet, there is a trick: you can derive a new helper class from the class in question and check whether sizeof(helper) == some_known_size. This 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.

Boost does this in its is_empty type trait implementation.

The general outline is as follows:

template <typename T>
struct is_empty {
    struct helper : T { int x; };
    static bool const VALUE = sizeof(helper) == sizeof(int);
};

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


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.


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_);
};


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜