Home > Net >  std::variant duplicate type cause no suitable constructor error(clang-1300.0.29.3)
std::variant duplicate type cause no suitable constructor error(clang-1300.0.29.3)

Time:10-17

Just wondering if this is the expected behaviour of std::variant, as well as the reasoning for this behaviour.

Simplified code to reproduce the error is as below:

double d= 1.0;
std::variant<std::monostate, double, double> v(d);

The error message is shown as below:

no suitable constructor exists to convert from "double" to "std::__1::variant<std::__1::monostate, std::__1::remove_cv_t<std::__1::remove_reference_t<double &>>, std::__1::remove_cv_t<std::__1::remove_reference_t<double &>>>"C/C  (415)

One solution I found now is to create a metafunction that removes duplicates from the variant type and then construct with the variable of the type double.

i.e.

distinct<std::variant<std::monostate, double, double>>v(d);
//distinct_t<std::variant<std::monostate, double, double>> -> std::variant<std::monostate, double>

If there is any better solution, please also let me know.

CodePudding user response:

Having multiple identical types in a std::variant is allowed. However, when the constructor of std::variant is invoked, overload resolution is performed to figure out which of the variant types it needs to hold. If you have 2 identical types, there's an ambiguity, and so you get an error.

You can specify which of the types you want to use explicitly

std::variant<std::monostate, double, double> v(std::in_place_index<1>, d); 

which will use the first double of the std::variant.

  • Related