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 ?

Drax
  • 12,682
  • 7
  • 45
  • 85
  • 3
    `std::optional` is no more :-( – Kerrek SB Dec 23 '13 at 13:01
  • (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.) – Kerrek SB Dec 23 '13 at 13:03
  • @KerrekSB That's sad for std::optional :(. For the implementation thing, it seems even [boost::optional implementation](http://www.boost.org/doc/libs/1_55_0/boost/optional/optional.hpp) puts its boolean before its data. – Drax Dec 23 '13 at 13:55
  • @KerrekSB why is `std::optional` not there anymore? whats the reason – Koushik Shetty Dec 26 '13 at 12:05
  • @Koushik: no idea. I guess the committee felt there was a lack of experience with it. – Kerrek SB Dec 26 '13 at 13:01
  • 1
    To be clear, `std::optional` _is_ a thing as of C++17. – xcvii Sep 04 '18 at 13:16

3 Answers3

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

Kerrek SB
  • 464,522
  • 92
  • 875
  • 1,084
26

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;
};
MB-F
  • 22,770
  • 4
  • 61
  • 116
3

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

Michael
  • 546
  • 1
  • 7
  • 19