It seems unions can be templated in c++11, they are used for example in the reference implementation of std::optional.
Was that possible before c++11 ?
As long as you are satisfied with automatic type inference, you can use a template constructor (of a non-template class). @updogliu: Absolutely.
Syntax for declaring a union is same as that of declaring a structure except the keyword struct. Note : Size of the union is the the size of its largest field because sufficient number of bytes must be reserved to store the largest sized field. To access the fields of a union, use dot(.)
In C++17 and later, the std::variant class is a type-safe alternative for a union. A union is a user-defined type in which all members share the same memory location. This definition means that at any given time, a union can contain no more than one object from its list of members.
If a union of two types is declared and one value is stored, but the union is accessed with the other type, the results are unreliable. For example, a union of float and int is declared. A float value is stored, but the program later accesses the value as an int .
Yes, it seems that this has always been allowed. A union is a class, and a template is either a function or a class template.
Relevant parts of the standards:
[temp]
The declaration in a template-declaration shall
— declare or define a function or a class, [...]
[class]
A union is a class defined with the class-key
union
(So one might argue that the new type trait std::is_class
is a slight misnomer; the traits are supposed to partition the space of types, and so is_union
is a separate, mutually exclusive trait.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With