Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can union be templated?

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 ?

like image 998
Drax Avatar asked Dec 23 '13 12:12

Drax


People also ask

Can constructors be templated?

As long as you are satisfied with automatic type inference, you can use a template constructor (of a non-template class). @updogliu: Absolutely.

How is a union declared?

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(.)

How do unions work in C++?

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.

When union is declared?

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 .


1 Answers

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.)

like image 136
Kerrek SB Avatar answered Sep 18 '22 17:09

Kerrek SB