如何从 mpl::vector 实例化模板

How to instantiate template from mpl::vector

我有一个 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>;

处理此类问题的最佳方法是什么?

谢谢。

您可以使用 boost::mpl::fold or std::make_index_sequence.

这两个代码片段都假定 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;

[全面披露:我是 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>
>{}, "");