gpt4 book ai didi

c++ - 匿名 union 和结构

转载 作者:IT老高 更新时间:2023-10-28 22:18:57 26 4
gpt4 key购买 nike

您将如何在标准 C++11/14 中执行此操作?因为如果我没记错的话,这不是具有匿名结构的标准兼容代码。

我希望以与您相同的方式访问成员。

template <typename some_type>
struct vec
{
union {
struct { some_type x, y, z; };
struct { some_type r, g, b; };

some_type elements[3];
};
};

最佳答案

是的,C++11 和 C++14 都不允许匿名结构。 This answer包含为什么会出现这种情况的一些推理。您需要命名结构,并且它们也不能在匿名 union 中定义。

§9.5/5 [class.union]

... The member-specification of an anonymous union shall only define non-static data members. [ Note: Nested types, anonymous unions, and functions cannot be declared within an anonymous union. —end note ]

所以将结构定义移到 union 之外。

template <typename some_type>
struct vec
{
struct xyz { some_type x, y, z; };
struct rgb { some_type r, g, b; };

union {
xyz a;
rgb b;
some_type elements[3];
};
};

现在,我们要求 some_typestandard-layout,因为这使得匿名 union 的所有成员 layout 兼容Here are the requirements对于标准布局类型。这些在标准的第 9/7 节中进行了描述。

然后,从 §9.2 [class.mem]

16   Two standard-layout struct (Clause 9) types are layout-compatible if they have the same number of non-static data members and corresponding non-static data members (in declaration order) have layout-compatible types (3.9).
18   If a standard-layout union contains two or more standard-layout structs that share a common initial sequence, and if the standard-layout union object currently contains one of these standard-layout structs, it is permitted to inspect the common initial part of any of them. Two standard-layout structs share a common initial sequence if corresponding members have layout-compatible types and either neither member is a bit-field or both are bit-fields with the same width for a sequence of one or more initial members.

对于数组成员,来自 §3.9/9 [basic.types]

... Scalar types, standard-layout class types (Clause 9), arrays of such types and cv-qualified versions of these types (3.9.3) are collectively called standard-layout types.

要确保 some_type 是标准布局,请在 vec

的定义中添加以下内容
static_assert(std::is_standard_layout<some_type>::value, "not standard layout");

std::is_standard_layouttype_traits header 中定义。现在您的 union 的所有 3 个成员都是标准布局,两个结构和数组是布局兼容的,因此 3 个 union 成员共享一个共同的初始序列,这允许您写入然后检查(读取)任何属于共同的成员初始序列(在你的情况下整个事情)。

关于c++ - 匿名 union 和结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25542390/

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