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 ?
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 ?
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.)
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;
};
In place of a union you can also use std::variant as of c++17 https://en.cppreference.com/w/cpp/utility/variant
© 2022 - 2024 — McMap. All rights reserved.
std::optional
is no more :-( – Glovestd::optional
not there anymore? whats the reason – Shoshoneanstd::optional
is a thing as of C++17. – Ibby