首页 > 解决方案 > 从数组构建可变元组以返回

问题描述

我想要一种方法来构建一个具有变量编号或条目的元组,该元组基于对象在成员变量容器(例如向量)中有多少条目。

这是我最好的结果。但是,不工作。我显然在返回值构造中遗漏了一些东西。假设m_values是一个容器,其中包含我想放入元组并返回的值。

template<typename... T>
std::tuple<T...> getValuesTuple()
{
    if (m_values[0].isValid())
    {
        return buildReturnTuple(0);
    }
    return std::tuple<T...>();
}

template<typename... T>
std::tuple<T...> buildReturnTuple(size_t i)
{
    if (i + 1 < MAX_VALUES && m_values[i + 1].isValid())
    {
        return std::tuple<T, T...>(m_values[i], buildReturnTuple(i + 1));
    }

    return std::tuple<T...>(m_values[i]...);
}

先感谢您!

标签: c++templatestuplesvariadic

解决方案


如果您在编译时知道数组的大小,可以通过以下方式完成:


#include <array>
#include <tuple>
#include <utility>

struct MyType {};

constexpr auto my_type_to_any_other_type(const MyType&) {
    // use if constexpr to return desired types
    return 0;
}

template<std::size_t N, std::size_t... Idx>
constexpr auto array_to_tuple_helper(const std::array<MyType, N>& a, std::index_sequence<Idx...>) {
    return std::make_tuple(my_type_to_any_other_type(a[Idx])...);
}

template<std::size_t N>
constexpr auto array_to_tuple(const std::array<MyType, N>& a) {
    return array_to_tuple_helper(a, std::make_index_sequence<N>{});
}

int main () {
    auto t = array_to_tuple(std::array<MyType, 1>{ MyType{} });
    return 0;
}

推荐阅读