Suppose I have a struct that contains a union with const
members, like so:
struct S
{
// Members
const enum { NUM, STR } type;
union
{
const int a;
const std::string s;
};
// Constructors
S(int t_a) : type(NUM), a(t_a);
S(const std::string & t_s) : type(STR), s(t_s);
};
So far, so good. But now say I want to write a copy-constructor for this type.
It doesn't seem like this involves doing anything nefarious, but since I need to initialize the const members in member initializers I don't see how to do this based on logic that depends on the type
member.
Questions:
Is it possible to write this constructor?
If not, is this essentially a syntactic oversight, or is there some fundamental reason that the language can't support such a thing?
const std::variant<int, std::string>
instead. – Bastinadostd::string
in a union you really need to use a tagged union. A non trivial type in a union deleted all of the unions special member functions and it isn't trivial to re-implement them correctly. – Ritype
member is for. (If you're just pointing out that I'll need to e.g. implement my own destructor, I understand that, but left it out of the code sample for brevity.) – Kaenelstd::variant
's source code should give you an example of how to do it, since it support const members. – Ria
ors
in the copy-constructor body without UB. Related: #33059217 – Fluidize