Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
199 views
in Technique[技术] by (71.8m points)

c++ - 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 obvious answer would be to just look at the code, but I would like to switch on this.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...