【问题标题】:Build variadic tuple from array to return从数组构建可变元组以返回
【发布时间】:2020-07-09 08:56:47
【问题描述】:

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

这是我最好的结果。但是,不工作。我显然在返回值构造中遗漏了一些东西。假设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]...);
}

提前谢谢你!

【问题讨论】:

  • 您必须在编译时知道向量中的元素数量。否则不可能做你想做的事
  • 可以看看std::make_tuple 吗?创建包含预期值的向量 v 然后使用 std::make_tuple(v.size(), begin(v), end(v)); 创建元组
  • @bartop 谢谢你的回答。我可以在编译时拥有一个具有(如代码中已经指出的)MAX_VALUES 常量数组大小的数组。

标签: c++ templates tuples variadic


【解决方案1】:

如果你在编译时就知道数组的大小,可以这样做:


#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;
}

【讨论】:

    【解决方案2】:

    C++ 中的变量类型是编译时属性。

    函数返回的类型是编译时属性。

    您要求执行的操作无法完成,因为 2 元素元组与 3 元素元组的类型不同。

    有基于std::variant 甚至std::any 的相关技术,但它们不太可能是您想要的。

    您需要退后一步,看看您的动机问题,它使您希望将数据存储为一个元组并找到不同的路径。

    【讨论】:

      猜你喜欢
      • 2020-05-08
      • 2021-04-04
      • 1970-01-01
      • 2020-02-20
      • 2017-06-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-10-30
      相关资源
      最近更新 更多