<type_traits>

類模板
<type_traits>

std::aligned_union

template <size_t Len, class... Types> struct aligned_union;
對齊聯合
獲取一個適合用作列表中任何物件型別的儲存的POD型別型別,並且大小至少為Len.

獲取的型別在成員型別中被別名為aligned_union::type.

請注意,這並非聯合型別,而是可以容納該聯合資料的資料型別。

模板引數

Len
儲存物件的最小大小(以位元組為單位)。
size_t 是一個無符號整數型別。
型別
型別列表。

成員型別

成員型別定義
型別一個POD型別,適合儲存列表中任何一種型別的物件,最小大小為型別大小至少為Len.

示例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
// aligned_union example
#include <iostream>
#include <type_traits>

union U {
  int i;
  char c;
  double d;
  U(const char* str) : c(str[0]) {}
};       // non-POD

typedef std::aligned_union<sizeof(U),int,char,double>::type U_pod;

int main() {
  U_pod a,b;              // default-initialized (ok: type is POD)
  new (&a) U ("hello");   // call U's constructor in place
  b = a;                  // assignment (ok: type is POD)
  std::cout << reinterpret_cast<U&>(b).i << std::endl;

  return 0;
}

輸出
104


另見