c++ - 用另一个元组中的元素填充一个元组

标签 c++ templates c++11 tuples

在如下模板中,如何从另一个更复杂的元组中的元素填充一个元组?

template<typename... Ts>
struct foo {
  std::tuple<std::vector<Ts>...> tuple;

  foo() {
    //populate tuple somehow
    //assume that no vector is empty
  }

  void func() {
    std::tuple<Ts...> back_tuple; // = ...
    //want to populate with the last elements ".back()" of each vector
    //how?
  }
};

我找不到任何元组的 push_back 机制,所以我不确定如何使用模板循环技巧来做到这一点。此外,我找不到任何类似模板的 initializer_list 用于不同类型来收集我的值然后传递到新元组中。有什么想法吗?

最佳答案

尝试这样的事情:

std::tuple<std::vector<Ts>...> t;

template <int...> struct Indices {};
template <bool> struct BoolType {};

template <int ...I>
std::tuple<Ts...> back_tuple_aux(BoolType<true>, Indices<I...>)
{
    return std::make_tuple(std::get<I>(t).back()...);  // !!
}

template <int ...I>
std::tuple<Ts...> back_tuple_aux(BoolType<false>, Indices<I...>)
{
    return back_tuple_aux(BoolType<sizeof...(I) + 1 == sizeof...(Ts)>(),
                          Indices<I..., sizeof...(I)>());
};

std::tuple<Ts...> back_tuple()
{
    return back_tuple_aux(BoolType<0 == sizeof...(Ts)>(), Indices<>());
}

(魔法发生在标记为 !! 的行中。)

关于c++ - 用另一个元组中的元素填充一个元组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17517735/

相关文章:

c++ - c和c++中函数指针的区别

c++ - 如何在 C++ 中修改 unordered_map 中的每个值

c++ - 字符数组顺序错误

django - Django 1.4 可以在模板中支持 elif 吗?

c++ - 类模板、函数成员定义

c++ - 从临时对象创建一对

c++ - 谁负责 futures 和 promises 的共享状态

c++ - map(long long int,long long int) 不适用于 key=1000 000 000(在 long long int 的范围内)

templates - foreach 中的 KnockoutJS 模板

c++ - 如何将 const std::shared_ptr 插入 std::map