How to get the i-th element from an std::tuple when i isn#39;t know at compile-time?(当我在编译时不知道时,如何从 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>
.
这篇关于当我在编译时不知道时,如何从 std::tuple 获取第 i 个元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:当我在编译时不知道时,如何从 std::tuple 获取第


基础教程推荐
- 在 C++ 中计算滚动/移动平均值 2021-01-01
- 我有静态或动态 boost 库吗? 2021-01-01
- 静态库、静态链接动态库和动态链接动态库的 .lib 文件里面是什么? 2021-01-01
- 如何在 C++ 中初始化静态常量成员? 2022-01-01
- 如何通过C程序打开命令提示符Cmd 2022-12-09
- 如何将 std::pair 的排序 std::list 转换为 std::map 2022-01-01
- 这个宏可以转换成函数吗? 2022-01-01
- C++结构和函数声明。为什么它不能编译? 2022-11-07
- 如何检查GTK+3.0中的小部件类型? 2022-11-30
- 常量变量在标题中不起作用 2021-01-01