c++ - 如何根据某些派生类型创建元组?

标签 c++ templates tuples

例如,我有类型

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/

相关文章:

python - 在元组列表中查找元素

python - 将元组与非元组列表进行比较

c++ - 如何逆时针排序具有n个元素的一个 vector 的所有点

c++ - 函数中引用的未解析的外部符号

c++ - 为什么缓存行仅适用于模拟化?

ruby - 如何在 ruby​​ 中缓存 Haml 模板

c++:什么是显式实例化

C++ 编程 ... 卡在 if..else if... 条件上

html - 为网站的不同页面制作 CSS 样式表

python - 为什么要实现两个如此相似的数据结构,如 List 和 Tuple