Search code examples
c++c++17variadic-templates

Create variant alternating value and array of value


I want to have something like:

template <typename... Ts>
using make_variant_t = /* ??? */;

such that, for instance, make_variant_t<Foo, Bar> evaluates as the type

 std::variant<Foo, std::vector<Foo>, Bar, std::vector<Bar>>

in that order. How, if it is possible, can this be achieved?


Solution

  • Alternative solution with std::tuple under the hood:

    namespace impl {
        template<class> struct tuple_to_variant;
    
        template<class... Ts>
        struct tuple_to_variant<std::tuple<Ts...>> {
            using type = std::variant<Ts...>;
        };
    }
    
    template<class... Ts>
    using make_variant_t = typename impl::tuple_to_variant<decltype(    
        std::tuple_cat(std::declval<std::tuple<Ts, std::vector<Ts>>>()...))>::type;