【问题标题】:Is it possible to use one tuple to index another?是否可以使用一个元组来索引另一个元组?
【发布时间】:2020-05-09 08:37:21
【问题描述】:

我有两个元组:一个包含我想要的数据,另一个包含第一个元组的索引列表。我想使用第二个元组使用std::get 访问第一个元组中的项目,但它似乎不起作用:

    const auto tup     = std::make_tuple(4, 5, 6);
    const auto indeces = std::make_tuple(0, 1, 2);

    const int index = std::get<0>(indeces);
    const int value = std::get<index>(tup); // won't compile
    // value should equal 4

当然,如果您认为 std::get 不会返回 constexpr,那么失败的原因就很明显了:

constexpr int index = std::get<0>(indeces); // won't compile

尽管如此,所有必要的信息都是在编译时提供的,所以我觉得应该有办法。有吗?


注意:我的indeces 元组开始它的生命是作为一个整数参数包。我把它做成了一个元组,因为我希望它更容易使用,但情况可能并非如此。如果有人能看到绕过indeces 元组并直接使用参数包整数来索引第一个元组的方法,那也是一个受欢迎的答案。

【问题讨论】:

  • 在 gcc 8 中工作:godbolt.org/z/VARw2q
  • std::array&lt;int, N&gt; 似乎比std::tuple&lt;int, ..., int&gt; 更合适。元组的替代方法是std::tuple&lt;std::integral_constant&lt;int, I1&gt;, ..., std::integral_constant&lt;int, IN&gt;&gt;

标签: c++ tuples c++17 stdtuple


【解决方案1】:

你应该把它们都做成constexpr

auto test()
{
    constexpr auto tup     = std::make_tuple(4, 5, 6);
    constexpr auto indeces = std::make_tuple(0, 1, 2);

    constexpr int index = std::get<0>(indeces);
    constexpr int value = std::get<index>(tup);
}

话虽如此,C++ 中的 const 积分有特殊处理,如果它们用编译时常量初始化,它们可以在编译时上下文中使用。所以你的代码也可以工作。

【讨论】:

  • @Evg ofc。谢谢
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-11-24
  • 1970-01-01
  • 2013-07-30
  • 2021-08-06
  • 1970-01-01
  • 2013-01-21
  • 1970-01-01
相关资源
最近更新 更多