如何访问integer_sequence的第n个值? [英] How to access n-th value of an integer_sequence?

查看:70
本文介绍了如何访问integer_sequence的第n个值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道如何访问 std :: integer_sequence 的第n个值。例如,给定类型

I would like to know how to access the n-th value of an std::integer_sequence. For example given a type

using foo = std::integer_sequence<int, 3, 1, 4>;

我想拥有类似的东西

auto i = get<foo, 2>(); // i = 4

标准库中是否可以执行此操作?如果没有,如果我想让它在C ++ 14(而不是C ++ 17)中工作,是否需要求助于迭代解决方案?

Is there something in the standard library to do that? If not, do I need to resort to an iterative solution if I want this to work in C++14 (not C++17) ?

推荐答案

据我所知,没有这种内置方法,但是您可以自己完成一些整洁的工作没有任何迭代的行:

There is no such built-in method as far as I'm aware but you can implement it yourself in a few neat lines without any iterations:

template<class T, T... Ints>
constexpr T get(std::integer_sequence<T, Ints...>, std::size_t i) {
    constexpr T arr[] = {Ints...};
    return arr[i];
}

在此处查看其工作方式: https://godbolt.org/z/yAfMeg

See how it works here: https://godbolt.org/z/yAfMeg

可以将参数提升为模板参数(以匹配您的示例),并添加了更多代码。

Arguments can be lifted into template parameters (to match your example) with a bit more code.

这篇关于如何访问integer_sequence的第n个值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆