Convert std::variant to another std::variant with super-set of types

前端 未结 2 940
时光说笑
时光说笑 2020-12-03 17:49

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 all

相关标签:
2条回答
  • 2020-12-03 18:37

    Options:

    • Write your own variant type, possibly inheriting from std::variant, that implements operator= and construction the way you want. Some work has to be done, because variant's constructors can do SFINAE tricks that might not work properly with your variant type; to that end, you want to do some SFINAE forwarding to base-variant yourself instead of naked using declarations.

    • Write a better ConvertVariant that doesn't require the source/destination types to be listed. You would return a convert helper template type that holds the source variant which has an operator std::variant<Ts...>()&& that calls something very much like your ConvertVariant.

    0 讨论(0)
  • 2020-12-03 18:45

    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);
    
    0 讨论(0)
提交回复
热议问题