<type_traits>

class template
<type_traits>

std::aligned_union

template <size_t Len, class... Types> struct aligned_union;
Aligned union
Obtains a POD type suitable for use as storage for any object whose type is listed in Types, and a size of at least Len.

The obtained type is aliased as member type aligned_union::type.

Notice that this type is not a union, but the type that could hold the data of such a union.

Template parameters

Len
The minimum size of the storage object, in bytes.
size_t is an unsigned integral type.
Types
A list of types.

Member types

member typedefinition
typeA POD type suitable to store an object of any of the types listed in Types, with a minimum size of Len.

Example

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;
}

Output:
104


See also