How to access n-th value of an integer_sequence? [duplicate]

狂风中的少年 提交于 2019-12-22 08:55:16

问题


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

I would like to have something like

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

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) ?


回答1:


There is no such built-in method as far as I'm aware but you can implement it itself 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];
}

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.



来源:https://stackoverflow.com/questions/53223910/how-to-access-n-th-value-of-an-integer-sequence

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!