The following code does not compile. Why is this restriction, and how can I bypass it? If I replace the variant declaration, it compiles.
struct PPP
{
int xxx;
PPP() : x(xxx) {} // error: No matching constructor for initialization of 'std::variant<Inner1, Inner2>'
struct Inner1
{
Inner1(int &x ) : c(x) {}
int &c;
};
struct Inner2
{
Inner2(int &x ) : c(x) {}
int &c;
};
struct Inner3 {};
std::variant<Inner1, Inner2> x;
// std::variant<Inner1, Inner3> x; // This will cause the code to compile
};
The
xxx
member is anint
.Inner1
andInner2
are both constructable from (a reference to) anint
, sox(xxx)
is ambiguous forstd::variant<Inner1, Inner2>
as the compiler doesn't know which type you want to construct inside thestd::variant
.When you use
std::variant<Inner1, Inner3>
instead, there is no ambiguity sinceInner3
can't be constructed from anint
.UPDATE: As Raymond mentioned in a comment, in this case you can use one of the
std::in_place_type_t
orstd::in_place_index_t
constructors ofstd::variant
to tell the compiler which inner type you want to create from theint
.