Can we detect empty classes in C++03?

303 views Asked by At

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 print 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!

1

There are 1 answers

10
Ben Voigt On BEST ANSWER

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 };
};