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

How to instantiate template from mpl::vector

本文关键字:实例化 vector mpl      更新时间:2023-10-16

我有一个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.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>
>{}, "");

您可以使用boost::mpl::foldstd::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;