如何从 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.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::fold
或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;
相关文章:
- 从C++实例化QML
- 设计一个只能由特定类实例化的类(如果可能的话,通过make_unique)
- 如何创建一个空的全局类并在启动时实例化它
- 在两个类中共享相同的函数调用,并在不需要时避免空实例化
- 约束和显式模板实例化
- 为什么包含windows.h会产生语法错误,从而阻止类的实例化?(C2146,C2065)
- 错误 C2280 / 在 std::vector 中实例化对象时复制构造函数出现问题?
- 有没有一种优雅的方法可以从 std::vector 实例化 boost::array
- 实例化 std::vector 的唯一元素,而无需复制构造函数
- 在头文件中包含std::vector会导致模板实例化错误
- 如何实例化没有默认构造函数的类型的 boost::fusion::vector 成员变量
- std::vector 不保留在实现中实例化的推回对象
- 如何从 mpl::vector 实例化模板
- 使用重复将灵气存储到 std::vector 中会导致模棱两可的类模板实例化
- JNI - 从 C++ Vector 实例化 Java ArrayList
- 用不同的对象实例化c++Vector
- C++实例化 std::vector<std::string> 具有固定数量的空字符串
- 避免内联显式实例化的 std::vector<T> 代码?(Visual Studio C++ 2008)
- 用默认值在Struct中实例化2D Vector
- vector实例化的模板参数无效