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>)'
U
is universe of all the types , and P has U, isn't P equals U ? I am having trouble understanding what problem you're trying to solve, may be I'm dumb :| – Pathicb=a
directly, to see the issue. – Garciab = ConvertVariant<decltype(b),decltype(a)>(a);
can be simplified tob = ConvertVariant<decltype(b)>(a);
and ifdecltype(b)
bothers you, you can have output parameter to your function to have something likeConvertVariantTo(a, b);
. – Sindee