是否有一个编译时函数/宏来确定c++ 0x结构体是否为POD

Is there a compile-time func/macro to determine if a C++0x struct is POD?

本文关键字:是否 c++ 0x 结构体 POD 编译 有一个 函数      更新时间:2023-10-16

我希望有一个c++ 0x static_assert来测试给定的结构类型是否为POD(以防止其他程序员无意中使用新成员破坏它)。例如,

struct A // is a POD type
{
   int x,y,z;
}
struct B // is not a POD type (has a nondefault ctor)
{
   int x,y,z; 
   B( int _x, int _y, int _z ) : x(_x), y(_y), z(_z) {}
}
void CompileTimeAsserts()
{
  static_assert( is_pod_type( A ) , "This assert should not fire." );
  static_assert( is_pod_type( B ) , "This assert will fire and scold whoever added a ctor to the POD type." );
}

我可以在这里使用某种is_pod_type()宏或内在的吗?我在任何c++ 0x文档中都找不到,当然,关于0x的网络信息仍然相当零碎。

c++ 0x在头文件<type_traits>中引入了一个类型特征库用于这种自省,并且有一个is_pod类型特征。我相信您会将其与static_assert结合使用,如下所示:

static_assert(std::is_pod<A>::value, "A must be a POD type.");

我使用的是ISO草案N3092,所以有可能这是过时的。我去查一下最新的草案,确认一下。

EDIT:根据最新的草案(N3242),这仍然有效。看来这就是解决办法了!