0

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!

Community
  • 1
  • 1
Nawaz
  • 341,464
  • 111
  • 648
  • 831
  • 1
    Duplicate-ish: http://stackoverflow.com/questions/4828992/is-there-an-easy-way-to-tell-if-a-class-struct-has-no-data-members – GManNickG Feb 14 '11 at 17:40

1 Answers1

4

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 };
};
Ben Voigt
  • 269,602
  • 39
  • 394
  • 697