[英]C++ tuple of vectors, create tuple from elements by index
I've got a template class, that has tuple, filled by vectors. 我有一个模板类,它有元组,由向量填充。
template<typename ...Ts>
class MyClass
{
public:
std::tuple<std::vector<Ts>...> vectors;
};
I want to get new tuple filled by vectors element on the specified index. 我想在指定的索引上使用vectors元素填充新元组。
template<typename ...Ts>
class MyClass
{
public:
std::tuple<std::vector<Ts>...> vectors;
std::tuple<Ts...> elements(int index)
{
// How can I do this?
}
};
Is this even possible? 这甚至可能吗?
You can accomplish it rather easily in C++14 it with the usual technique of a helper function that accepts an index sequence as an added parameter: 您可以使用通常的辅助函数技术在C ++ 14中轻松完成它,该函数接受索引序列作为附加参数:
template<std::size_t... I>
auto elements_impl(int index, std::index_sequence<I...>)
{
return std::make_tuple(
std::get<I>(vectors).at(index)...
);
}
auto elements(int index)
{
return elements_impl(index, std::index_sequence_for<Ts...>{});
}
It just calls std::get<I>
for the ordinal of each type, and then calls at
on the vector at that place. 它只是调用std::get<I>
为每种类型的顺序,然后调用at
在那个地方的载体。 I used at
in case the vectors aren't all holding an item at that index, but you can substitute for operator[]
if your case doesn't require the check. 我以前at
的情况下,载体是不是所有持有该索引处的项目,但你可以代替operator[]
如果你的情况下,不需要检查。 All the results are then sent to make_tuple
to construct the result tuple object. 然后将所有结果发送到make_tuple
以构造结果元组对象。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.