【问题标题】:C++ tuple of vectors, create tuple from elements by indexC ++向量元组,按索引从元素创建元组
【发布时间】:2018-01-31 10:19:53
【问题描述】:

我有一个模板类,它有元组,由向量填充。

template<typename ...Ts>
class MyClass
{
    public:
        std::tuple<std::vector<Ts>...> 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++ c++11 templates c++14


【解决方案1】:

您可以在 C++14 中使用通常的辅助函数技术轻松完成它,该辅助函数接受 index sequence 作为附加参数:

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&lt;I&gt;,然后在该位置的向量上调用at。我使用了at,以防向量并非全部包含该索引处的项目,但如果您的情况不需要检查,您可以替换operator[]。然后将所有结果发送到make_tuple 以构造结果元组对象。

【讨论】:

    猜你喜欢
    • 2016-09-30
    • 1970-01-01
    • 2021-04-23
    • 2022-01-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-24
    • 1970-01-01
    相关资源
    最近更新 更多