Можем ли мы обнаружить пустые классы в C++03?
Возможный дубликат:
Есть ли простой способ определить, нет ли в классе / структуре данных-членов?
Можем ли мы обнаружить emply классы, возможно, используя шаблон?
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
Только C++03, но не C++0x!
1 ответ
Решение
Если ваш компилятор поддерживает пустую оптимизацию базового класса, да.
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 };
};
Лучше:
#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 };
};