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

前端 未结 4 867
后悔当初
后悔当初 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: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 
    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).

提交回复
热议问题