【问题标题】:How to instantiate template from mpl::vector如何从 mpl::vector 实例化模板
【发布时间】:2015-01-29 04:54:27
【问题描述】:

我有一个 mpl::vector 并且想要使用向量元素作为模板参数来实例化一个模板。这是怎么做的?是否可以使用参数包来合并额外的 mpl::vector 元素?

例如:

struct A; struct B; struct C; struct D;

using args = mpl::vector<A, B, C, D>;

template<typename argA, typename argB, typename argC...>
struct derived_type;

using type_from_vector = derived_type<args>;

处理此类事情的最佳方法是什么?

谢谢。

【问题讨论】:

    标签: c++ variadic-templates boost-mpl


    【解决方案1】:

    [全面披露:我是 Boost.Hana 的开发者]

    我知道这个问题是关于 Boost.MPL 的,但请让我使用 Boost.Hana 回答 图书馆(仍在开发中)。如果你使用的是最近的 Clang,你 可能想试试这个库;它可以做 Boost.MPL 可以做的一切 做,但它非常努力地使它不那么痛苦。给你:

    #include <boost/hana/type_list.hpp>
    #include <boost/hana/type.hpp>
    #include <type_traits>
    namespace hana = boost::hana;
    
    struct A; struct B; struct C; struct D;
    constexpr auto args = hana::type_list<A, B, C, D>;
    
    template<typename argA, typename argB, typename ...argC>
    struct derived_type;
    
    using type_from_vector = decltype(
        hana::unpack(args, hana::template_<derived_type>)
    )::type;
    
    static_assert(std::is_same<
        type_from_vector,
        derived_type<A, B, C, D>
    >{}, "");
    

    【讨论】:

    • 您的 hana 库看起来很有前途。 MPL 编程确实需要针对 c++11/14 进行更新。解决我的问题的非常干净的用法绝对适合您的图书馆。不幸的是,我需要一个生产解决方案来解决今天的问题,但会继续关注你的 mpl/fusion/phoenix 升级!
    • 谢谢!我正在努力开发这个库,目标是在今年春天将它包含在 Boost 中。如果一切都按计划进行,您也许可以在不久的将来将它作为 Boost 版本的一部分在生产中使用(鉴于最近的编译器)。
    【解决方案2】:

    您可以使用boost::mpl::foldstd::make_index_sequence

    这两个代码 sn-ps 都假定using namespace boost::mpl;

    使用boost::mpl::fold

    template <typename TList, typename T> struct ExtendTList;
    template<typename T, typename... Ts>
    struct ExtendTList<derived_type<Ts...>, T>
    {
      using type = derived_type<Ts..., T>;
    };
    
    using type_from_vector = fold<args, derived_type<>, ExtendTList<_1, _2>>::type;
    

    使用std::make_index_sequence

    template <typename V, template<typename...> T, typename Seq>
    struct MakeFromTypesAtIndices;
    template <typename V, template<typename...> T, size_t ... Indices>
    struct MakeFromTypesAtIndices<V, T, std::integer_sequence<size_t, Indices...>>
    {
      using type = T< at<V, Indices>... >;
    };
    
    using type_from_vector = MakeFromTypesAtIndices<args, derived_type, std::make_index_sequence<size<args>::value>>::type;
    

    【讨论】:

    • 感谢您的帮助。我想这里的教训之一是,当有疑问时,要弃牌。
    猜你喜欢
    • 2023-03-17
    • 1970-01-01
    • 2023-03-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多