在如下的模板中,如何从另一个更复杂的元组中的元素填充元组?
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机制,因此我不确定如何使用模板循环技巧来执行此操作。此外,我找不到任何类似初始化器列表的模板来收集我的值,然后传递给新的元组。有什么想法吗?
答案 0 :(得分:3)
尝试这样的事情:
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<>());
}
(魔法发生在标有!!
的行中。)