gpt4 book ai didi

c++ - 是否有编译时函数/宏来确定 C++0x 结构是否为 POD?

转载 作者:IT老高 更新时间:2023-10-28 21:41:29 26 4
gpt4 key购买 nike

我想要一个 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> 中引入了类型特征库对于这种内省(introspection),有一个 is_pod类型特征。我相信你会和 static_assert 一起使用。如下:

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

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

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

关于c++ - 是否有编译时函数/宏来确定 C++0x 结构是否为 POD?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7169131/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com