Drax
Drax

Reputation: 13288

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 ?

Upvotes: 29

Views: 12198

Answers (3)

MB-F
MB-F

Reputation: 23637

Yes, a particularly useful application is to represent a type simultaneously as a byte array:

template <typename T>
union test
{
    unsigned char ch[sizeof(T)];
    T variable;
};

Upvotes: 27

Michael
Michael

Reputation: 566

In place of a union you can also use std::variant as of c++17 https://en.cppreference.com/w/cpp/utility/variant

Upvotes: 3

Kerrek SB
Kerrek SB

Reputation: 477040

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

Upvotes: 30

Related Questions