Creating a variant type of all possible map of key-value types at compile time, where the key and value types are specified from a tuple of types

佐手、 提交于 2019-12-24 10:16:38

问题


Currently, I have a variant of map types, where I hard-code all variations of key-value pairs, as such:

// for example, if we support std::string and int types as key-value pair
using MapCombinator = std::variant<
    std::map<std::string, std::string>, 
    std::map<std::string, int>, 
    std::map<int, std::string>, 
    std::map<int, int>>;

In the real case, I need to support key-value pairs of all fundamental types, in addition to std::string. This is why, I would like to only specify a tuple of types, something more like this:

using KVTypes = std::tuple<std::string, int, etc...>;
using MapCombinator = MapCombinatorImpl::type;

where MapCombinatorImpl contains the template-meta-programming logic that creates the final variant type. I would expect something as such:

template<typename... SupportedTypes>
struct MapCombinatorImpl {
    typedef ??? type;
};

I don't want to use macros for this, and if it is too complicated to do with template-meta-programming, I'll support only a manageable subset of fundamental types.

Help appreciated for the implementation with template-meta-programming.


回答1:


You might use:

template <typename Tuple, typename Seq> struct MapCombinatorImpl;

template <typename Tuple, std::size_t ... Is>
struct MapCombinatorImpl<Tuple, std::index_sequence<Is...>>
{
    constexpr static std::size_t size = std::tuple_size<Tuple>::value;
    using type = std::variant<std::map<std::tuple_element_t<Is / size, Tuple>,
                                       std::tuple_element_t<Is % size, Tuple>>...>;
};

template <typename ... Ts>
using MapCombinator =
    typename MapCombinatorImpl<std::tuple<Ts...>,
                               std::make_index_sequence<sizeof...(Ts) * sizeof...(Ts)>
                              >::type;

Demo




回答2:


You can use 2-level parameter pack expansion:

namespace detail {
    template<class T, class... Ts>
    using pair_list = std::tuple<std::map<T, Ts>...>;

    template<class Tuple> struct huge_variant_impl;
    template<class... Ts>
    struct huge_variant_impl<std::tuple<Ts...>> {
        using type = std::variant<Ts...>;
    };
}

template<typename... Ts>
struct huge_variant {
    using type = typename detail::huge_variant_impl<
        decltype(std::tuple_cat(std::declval<detail::pair_list<Ts, Ts...>>()...))
        >::type;
};


来源:https://stackoverflow.com/questions/49491838/creating-a-variant-type-of-all-possible-map-of-key-value-types-at-compile-time

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!