分享方式:


aligned_union 類別

提供夠大並適當對齊的 POD 類型來儲存等位類型,以及所需的大小。

語法

template <std::size_t Len, class... Types>
struct aligned_union;

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

參數

Len
等位中最大類型的對齊值。

類型
基礎等位中的不同類型。

備註

使用類別範本取得將等位儲存在未初始化儲存體中聯集所需的對齊和大小。 成員 typedef type 會將 POD 類型命名為適合儲存在 Types 所列的任何類型;最小大小為 Len 。 類型的 std::size_t 靜態成員 alignment_value 包含類型中列出的 所有類型最嚴格的對齊方式。

範例

下列範例示範如何使用 aligned_union 配置對齊的堆疊緩衝區來放置等位。

// std__type_traits__aligned_union.cpp
#include <iostream>
#include <type_traits>

union U_type
{
    int i;
    float f;
    double d;
    U_type(float e) : f(e) {}
};

typedef std::aligned_union<16, int, float, double>::type aligned_U_type;

int main()
{
    // allocate memory for a U_type aligned on a 16-byte boundary
    aligned_U_type au;
    // do placement new in the aligned memory on the stack
    U_type* u = new (&au) U_type(1.0f);
    if (nullptr != u)
    {
        std::cout << "value of u->i is " << u->i << std::endl;
        // must clean up placement objects manually!
        u->~U_type();
    }
}
value of u->i is 1065353216

需求

標頭: < type_traits>

命名空間:std

另請參閱

<type_traits>
alignment_of 類別