如何基于一些派生类型生成元组
How to make a tuple based on some derived types?
例如,我有类型
template<unsigned i> struct Element;
template struct Element<0> {typedef int Type};
template struct Element<1> {typedef float Type};
template struct Element<2> {typedef double Type};
static const int COUNT = 3;
并希望制作一个类型为的元组
std::tuple<Element<0>::Type, Element<1>::Type, Element<2>::Type>
如果COUNT是常数,但不总是3,该怎么办?
基本上有两种方法,仅在思想上不同:索引(当您有(功能性的)可变模板可用时),或在进行过程中手动构建元组(当您使用Visual C++时)。
指数:
template<unsigned... Is> struct seq{};
template<unsigned I, unsigned... Is>
struct gen_seq : gen_seq<I-1, I-1, Is...>{};
template<unsigned... Is>
struct gen_seq<0, Is...>{ using type = seq<Is...>; };
template<unsigned N, template<unsigned> class TT,
class Seq = typename gen_seq<N>::type>
struct tuple_over{};
template<unsigned N, template<unsigned> class TT, unsigned... Is>
struct tuple_over<N, TT, seq<Is...>>{
using type = std::tuple<typename TT<Is>::type...>;
};
手动递归:
template<unsigned N, template<unsigned> class TT, class TupleAcc = std::tuple<>>
struct tuple_over{
using tt_type = typename TT<N-1>::type;
// since we're going from high to low index,
// prepend the new type, so the order is correct
using cat_type = decltype(std::tuple_cat(std::declval<std::tuple<tt_type>>(), std::declval<TupleAcc>()));
using type = typename tuple_over<N-1, TT, cat_type>::type;
};
template<template<unsigned> class TT, class Tuple>
struct tuple_over<0, TT, Tuple>{ using type = Tuple; }
两个版本的用法相同:
using result = tuple_over<COUNT, Element>::type;
指数的实例
手动递归的实例。
这里有一种可能的方法。给定您的类模板定义:
template<unsigned i> struct Element;
template<> struct Element<0> { typedef int type; };
template<> struct Element<1> { typedef float type; };
template<> struct Element<2> { typedef double type; };
你可以利用通常的索引框架来写这样的东西:
#include <tuple>
namespace detail
{
template<int... Is>
struct seq { };
template<int N, int... Is>
struct gen_seq : gen_seq<N - 1, N - 1, Is...> { };
template<int... Is>
struct gen_seq<0, Is...> : seq<Is...> { };
template<template<unsigned int> class TT, int... Is>
std::tuple<typename TT<Is>::type...> make_tuple_over(seq<Is...>);
}
template<template<unsigned int> class TT, int N>
using MakeTupleOver =
decltype(detail::make_tuple_over<TT>(detail::gen_seq<N>()));
这就是你在程序中使用它的方式:
#include <type_traits> // For std::is_same
int main()
{
static_assert(
std::is_same<
MakeTupleOver<Element, 3>,
std::tuple<int, float, double>
>::value, "!");
}
这是一个的实际示例。
相关文章:
- 在C++中,如何通过几种类型从元组中选择多个元素
- 将元组类型扩展为可变参数模板?
- 时间复杂度 当具有复合数据类型(如元组或对)时?
- 创建派生自可变参数模板包的类型元组
- 枚举元组类型的最佳方法?
- 验证(使用 static_assert)元组类型是否遵循某种顺序(有状态编译时检查)
- C 元组类型用于功能参数类型
- C++ 如何根据部分特化制作 std::元组类型?
- 在运行时基于基础元组类型生成元素
- 模板函数,具有元组类型子集的相应参数
- 获取级联元组类型;组合result_of和tuple_cat
- 类元组类型(tuple,pair)的模板重载
- 如何将l值元组类型转换为值元组类型
- 使用C++元组类型作为映射中的键
- 转换元组类型
- 如何从旧的元组类型和boost中的类型创建新的元组类型
- 使用另一个构造一个具体的boost::元组类型
- 如何反转元组类型中元素类型的顺序
- 增强元组类型的hana大小
- 测试类型 V 是否属于没有变变量的元组类型<...>