Ambiguity and Complex Types
What if we want to create objects of complex types? What if there's ambiguity when you initialize std::variant? Read below to find out the answers.
We'll cover the following...
Let’s Discuss Ambiguity
What if you have an initialization like:
Press + to interact
std::variant<int, float> intFloat { 10.5 }; // conversion from double?
The value 10.5 could be converted to int
or float
, and the compiler doesn’t know which
conversion should be applied. It might report a few pages of compiler errors, however.
But you can easily handle such errors by specifying which type you’d like to create:
Press + to interact
std::variant<int, float> intFloat { std::in_place_index<0>, 10.5f };// orstd::variant<int, float> intFloat { std::in_place_type<int>, 10.5f };
Let’s Discuss Complex Types
Similarly to std::optional
, if you want to efficiently create objects that require several constructor arguments - then use std::in_place_index
or std::in_place_type
:
For example:
Press + to interact
std::variant<std::vector<int>, std::string> vecStr{std::in_place_index<0>, { 0, 1, 2, 3 } // initializer list passed into vector};
...