我们可以在C ++ 03中检测空类吗?

时间:2011-02-14 17:34:44

标签: c++ templates empty-class c++03

可能重复:
{{3p>

我们可以使用模板检测空类吗?

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 个答案:

答案 0 :(得分:4)

如果您的编译器支持空基类优化,那么。

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