[英]C++ tuple of vectors, create tuple from elements by index
我有一個模板類,它有元組,由向量填充。
template<typename ...Ts>
class MyClass
{
public:
std::tuple<std::vector<Ts>...> vectors;
};
我想在指定的索引上使用vectors元素填充新元組。
template<typename ...Ts>
class MyClass
{
public:
std::tuple<std::vector<Ts>...> vectors;
std::tuple<Ts...> elements(int index)
{
// How can I do this?
}
};
這甚至可能嗎?
您可以使用通常的輔助函數技術在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...>{});
}
它只是調用std::get<I>
為每種類型的順序,然后調用at
在那個地方的載體。 我以前at
的情況下,載體是不是所有持有該索引處的項目,但你可以代替operator[]
如果你的情況下,不需要檢查。 然后將所有結果發送到make_tuple
以構造結果元組對象。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.