将 std::variant 转换为具有超类型集的另一个 std::variant

2022-01-12 00:00:00 type-conversion c++ variant c++17

我有一个 std::variant 我想将其转换为另一个具有其类型超集的 std::variant.有没有一种方法可以让我简单地将一个分配给另一个?

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;
}

我希望能够简单地编写 b = a 来进行转换,而不是通过这种复杂的转换设置.不会污染 std 命名空间.

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.

简单地写 b = a 会出现以下错误:

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>)'

推荐答案

这是Yakk第二个选项的实现:

This is an implementation of Yakk's second option:

template <class... Args>
struct variant_cast_proxy
{
    std::variant<Args...> v;

    template <class... ToArgs>
    operator std::variant<ToArgs...>() const
    {
        return std::visit([](auto&& arg) -> std::variant<ToArgs...> { return arg ; },
                          v);
    }
};

template <class... Args>
auto variant_cast(const std::variant<Args...>& v) -> variant_cast_proxy<Args...>
{
    return {v};
}

您可能希望对其进行微调以实现转发语义.

You might want to fine tune it for forwarding semantics.

你可以看到它的使用很简单:

And as you can see its use is simple:

std::variant<int, char> v1 = 24;
std::variant<int, char, bool> v2;

v2 = variant_cast(v1);

相关文章