std::aligned_union_C++中文网

提供嵌套类型 type ,它是平凡的标准布局类型,且其大小和对齐适合用作任何列于 Types 的类型的一个对象的未初始化存储。存储的大小至少为 Lenstd::aligned_union 亦确定所有 Types 中最严格(最大)的对齐要求,使之可用作常量 alignment_value

sizeof...(Types) == 0 或若 Types 中的任何类型不是完整对象类型,则行为未定义。

是否支持任何扩展对齐是实现定义的。

添加 aligned_union 的特化的程序行为未定义。

成员类型

 
名称 定义
type 适用于存储来自 Types 的任何类型的平凡类型

辅助类型

template< std::size_t Len, class... Types >
using aligned_union_t = typename aligned_union<Len,Types...>::type;

(C++14 起)

成员常量

所有 Types 的最严格对齐
(公开静态成员常量)

可能的实现

#include <algorithm>
template <std::size_t Len, class... Types>
struct aligned_union
{
    static constexpr std::size_t alignment_value = std::max({alignof(Types)...});
 
    struct type
    {
      alignas(alignment_value) char _s[std::max({Len, sizeof(Types)...})];
    };
};

示例

缺陷报告

下列更改行为的缺陷报告追溯地应用于以前出版的 C++ 标准。

DR 应用于 出版时的行为 正确行为
LWG 2979 C++11 不要求完整类型 要求完整类型

参阅