例如,我有类型
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 怎么办?
最佳答案
基本上有两种方法,只是想法不同: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.
关于c++ - 如何根据某些派生类型创建元组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17602761/