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

前端 未结 4 866
后悔当初
后悔当初 2020-12-07 00:20

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

相关标签:
4条回答
  • 2020-12-07 01:07

    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.

    0 讨论(0)
  • 2020-12-07 01:10

    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_);
    };
    
    0 讨论(0)
  • 2020-12-07 01:15

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

    0 讨论(0)
  • 2020-12-07 01:22

    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 讨论(0)
提交回复
热议问题