I have a std::variant
that I'd like to convert to another std::variant
that has a super-set of its types. Is there a way of doing it than that allows me to simply assign one to the other?
template <typename ToVariant, typename FromVariant>
ToVariant ConvertVariant(const FromVariant& from) {
ToVariant to = std::visit([](auto&& arg) -> ToVariant {return arg ; }, from);
return to;
}
int main()
{
std::variant<int , double> a;
a = 5;
std::variant <std::string, double, int> b;
b = ConvertVariant<decltype(b),decltype(a)>(a);
return 0;
}
I'd like to be able to simply write b = a
in order to do the conversion rather than going through this complex casting setup. Without polluting the std
namespace.
Edit: Simply writing b = a
gives the following error:
error C2679: binary '=': no operator found which takes a right-hand operand of type 'std::variant<int,double>' (or there is no acceptable conversion)
note: while trying to match the argument list '(std::variant<std::string,int,double>, std::variant<int,double>)'