基本上有两种方法,仅在想法上有所不同:索引(当您有(功能)可变参数模板可用时),或者在您进行时手动构建元组(当您有 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;
指数的活生生的例子。
手动递归的实时示例。