Can union be templated?
Asked Answered
T

3

29

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 ?

Tiernan answered 23/12, 2013 at 12:27 Comment(6)
std::optional is no more :-(Glove
(It's an odd decision to place the init flag at the top of the class and not the data member. I would have thought that cheap dereferencing would be desirable moreso than validity checking.)Glove
@KerrekSB That's sad for std::optional :(. For the implementation thing, it seems even boost::optional implementation puts its boolean before its data.Tiernan
@KerrekSB why is std::optional not there anymore? whats the reasonShoshonean
@Koushik: no idea. I guess the committee felt there was a lack of experience with it.Glove
To be clear, std::optional is a thing as of C++17.Ibby
G
30

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

Glove answered 23/12, 2013 at 12:33 Comment(1)
I did not even know that "A union is a class" ! Glad i asked this question :)Tiernan
J
27

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;
};
Jiffy answered 23/12, 2013 at 12:34 Comment(0)
F
3

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

Farley answered 29/11, 2019 at 23:22 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.