当我在编译时不知道时,如何从 std::tuple 获取第 i 个元素?
我有一个 std::size_t
类型的变量 i
和一个 std::tuple
类型的元组.我想获取元组的 i
-th 元素.我试过这个:
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
' 类型的非类型模板参数(又名'unsigned long
')不是整数常量表达式
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
[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>
.
相关文章