I am having trouble initializing a union which contains const
members in C++11.
In C++20 the problem is avoided by using designated initializers. Example :
union my_union
{
const void* ptr;
const double dbl;
};
my_union foo = { .dbl = 42.1 };
However, in C++11 this feature is not available, and it seems the union is always initialized by its first member.
Since the members are const, it also seems that the only way to set a member is via initialization.
I considered using a placement new expression to overwrite the union but I am confused by the lifetime issues related to unions, specifically if placement new "activates" the intended member (https://godbolt.org/z/z4nMTGGeq).
#include <iostream>
#include <new>
union my_union
{
const void* ptr;
const double dbl;
};
int main()
{
my_union foo{};
new(&foo) double {42.1};
std::cout << foo.dbl;
}
Is this solution well defined? Or is their better solutions?
The language version and const
-ness of the union members are imposed and outside of my control.
Edit : The union is defined by a 3rd party header that can't be changed.
You can give the union constructors for the different members:
#include <iostream>
union my_union
{
my_union(void* ptr_) : ptr(ptr_) {}
my_union(double dbl_) : dbl(dbl_) {}
const void* ptr;
const double dbl;
};
int main()
{
my_union foo{42.1};
std::cout << foo.dbl;
}
Outputs:
42.1
Which can be seen in this live example.