基本上有兩種方法,它們只有不同的概念:Indices(當你有(功能)可變參數模板可用時),或者當你走時(當你有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;
Live example for indices.
Live example for manual recursion.
來源
2013-07-11 20:40:39
Xeo
您使用的是什麼C++版本? – CookieOfFortune
MSVC 2012 v110,但我也可以使用v120_CTP_Nov2012。 – user1899020
有一個包,比如'unsigned ...'? –