开发者

Can we detect empty classes in C++03? [duplicate]

开发者 https://www.devze.com 2023-02-10 05:14 出处:网络
This question already has answers here: Closed 11 years ago. Possible Duplicate: Is there an easy way to tell if a class/struct has no data members?
This question already has answers here: Closed 11 years ago.

Possible Duplicate:

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

Can we detect emply classes, possibly using template?

struct A {};
struct B { char c;};

std::cout << is_empty<A>::value; //should print 0
std::cout << is_empty<B>::value; //should prin开发者_运维问答t 1

//this is important, the alleged duplicate doesn't deal with this case!
std::cout << is_empty<int>::value; //should print 0

Only C++03 only, not C++0x!


If your compiler supports the empty base class optimization, yes.

template <typename T>
struct is_empty
{
    struct test : T { char c; };
    enum { value = sizeof (test) == sizeof (char) };
};

template <>
struct is_empty<int>
{
    enum { value = 0 };
};

Better:

#include  <boost/type_traits/is_fundamental.hpp>
template <bool fund, typename T>
struct is_empty_helper
{
    enum { value = 0 };
};

template <typename T>
struct is_empty_helper<false, T>
{
    struct test : T { char c; };
    enum { value = sizeof (test) == sizeof (char) };
};

template<typename T>
struct is_empty
{
    enum { value = is_empty_helper<boost::is_fundamental<T>::value, T>::value };
};
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号