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

不羁的心 提交于 2019-11-28 01:48:47
Konrad Rudolph

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

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