I would like to pick the union member initialized in the constructor based on an argument. The following is an example that works:
struct A {
union {
int i;
float f;
};
A(double d, bool isint) {
if (isint) new(&i) int(d);
else new(&f) float(d);
}
};
While I'm using int
and float
, the goal is to work with other more complex types (but still allowable in a C++14 union), hence the use of placement-new (and not an assignment).
The problem is that this constructor cannot be constexpr
as placement-new is not allowed in constexpr
methods. Is there any way around this (other than making the isint
argument part of the formal type system)? Some type of conditional initalizer list would work, but I'm unaware of a way to do it.