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 获取第
基础教程推荐
- 为什么 typeid.name() 使用 GCC 返回奇怪的字符以及如 2022-09-16
- GDB 显示调用堆栈上函数地址的当前编译二进制文 2022-09-05
- CString 到 char* 2021-01-01
- 为什么派生模板类不能访问基模板类的标识符? 2021-01-01
- 初始化列表*参数*评估顺序 2021-01-01
- 非静态 const 成员,不能使用默认赋值运算符 2022-10-09
- 如果我为无符号变量分配负值会发生什么? 2022-01-01
- 通过引用传递 C++ 迭代器有什么问题? 2022-01-01
- 我应该对 C++ 中的成员变量和函数参数使用相同的名称吗? 2021-01-01
- 为什么 RegOpenKeyEx() 在 Vista 64 位上返回错误代码 2021-01-01
