I have a std::variant that I would like to convert to another std::variant , which has a super-set of its types. Is there a way to do this than it allows me to simply assign one to another?
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 would just like to write b = a to do the conversion, and not go through this complicated casting setting. Without polluting the std .
Edit: just 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>)'
Bomaz source share