是否可以使用一个元组来索引另一个元组



我有两个元组:一个包含我想要的数据,另一个包含第一个元组的索引列表。我想使用第二个元组来使用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元组最初是作为int的参数包。我把它做成了一个元组,因为我希望它更容易使用,但事实可能并非如此。如果有人能找到绕过indeces元组并直接使用参数pack-ints对第一个元组进行索引的方法,那也是一个受欢迎的答案。

您应该让它们都是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++中的常量积分有特殊处理,如果它们是用编译时常数初始化的,那么它们可以在编译时上下文中使用。所以您的代码也可以工作。

最新更新