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

孤街浪徒 提交于 2019-11-26 22:03:07

问题


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.


回答1:


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




回答2:


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.




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



回答4:


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



来源:https://stackoverflow.com/questions/4828992/is-there-an-easy-way-to-tell-if-a-class-struct-has-no-data-members

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!