【问题标题】:Is there a compile-time func/macro to determine if a C++0x struct is POD?是否有编译时函数/宏来确定 C++0x 结构是否为 POD?
【发布时间】:2011-11-02 09:42:56
【问题描述】:

我想要一个 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 中,结构 B 不是 POD,因为它没有普通默认构造函数(请参阅 N3242 中的 9.0.10 和 9.0.6)。我不确定究竟什么才是微不足道的默认构造函数(参见 12.1.5),但我怀疑添加 B() = default; 可能会将 struct B 变成 C++0x POD。

标签: c++ typetraits static-assert c++11


【解决方案1】:

C++0x 在头文件 <type_traits> 中引入了一个类型特征库来进行这种内省,并且有一个 is_pod 类型特征。我相信你会和static_assert一起使用如下:

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

我为此使用了 ISO 草案 N3092,所以这有可能已经过时了。我会在最近的草稿中查找这一点以确认它。

编辑:根据最新草案 (N3242),这仍然有效。看起来就是这样做的方法!

【讨论】:

  • 请注意,在 C++0x 中,POD 定义已经放宽和拆分。所以现在还有std::is_trivially_copyable&lt;&gt;std::is_standard_layout&lt;&gt;(参见链接的N3242)。请参阅stackoverflow.com/questions/6496545/… 了解可轻松复制标准布局 的含义。
  • @Sjoerd- 感谢您的链接!我不知道。
  • 另外,is_pod 是在 C++03 的 TR1 中引入的(或者,从技术上讲,在此之前的 Boost.TypeTraits 中)——它只在 C 中被 标准 ++0x。
猜你喜欢
  • 1970-01-01
  • 2012-05-30
  • 1970-01-01
  • 1970-01-01
  • 2014-10-08
  • 1970-01-01
  • 1970-01-01
  • 2012-12-26
  • 2020-05-20
相关资源
最近更新 更多