当我在编译时不知道时,如何从std :: tuple获取第i个元素? [英] How to get the i-th element from an std::tuple when i isn't know at compile-time?
问题描述
我有一个类型为 std :: size_t
的变量 i
和一个类型为 std :: tuple
。我想获得元组的 i
个元素。我试过这个:
I have a variable i
of type std::size_t
and a tuple of type std::tuple
. I want to get the i
-th element of the tuple. I tried this:
// bindings... is of type const T&...
auto bindings_tuple = std::make_tuple(bindings...);
auto binding = std::tuple_element<i, const T&...>(bindings_tuple);
但是我收到此编译错误,指出第一个模板参数必须是整数常量表达式:
But I get this compile error saying that the first template argument must be an integral constant expression:
错误:类型'
std :: size_t
'的非类型模板参数'无符号长
')不是整数常量表达式
error: non-type template argument of type '
std::size_t
' (aka 'unsigned long
') is not an integral constant expression
是否可能获取元组的第 i
个元素,以及如何做到这一点?
Is it possible to get the i
-th element of a tuple, and how to do that?
如果可能的话,我想不使用boost来做到这一点。
推荐答案
不能。那不是元组的目的。如果需要动态访问元素,请使用 std :: array< T,N>
,这几乎与 std :: tuple< T相同,...,T>
,但为您提供动态的 [i]
运算符;甚至是完全动态的容器,例如 std :: vector< T>
。
You cannot. That's not what a tuple is for. If you need dynamic access to an element, use std::array<T,N>
, which is almost identical to std::tuple<T,...,T>
but gives you the dynamic [i]
-operator; or even a fully dynamic container like std::vector<T>
.
这篇关于当我在编译时不知道时,如何从std :: tuple获取第i个元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!