Can union be templated?
In place of a union you can also use std::variant as of c++17 https://en.cppreference.com/w/cpp/utility/variant
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;
};
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.)