c++ - 获取对元组元素的引用

标签 c++ reference stl tuples

假设我有一个包含类型 ABC 的元组:

std::tuple<A,B,C> t;

我怎样才能提取对其中一个元素的引用,一个可变引用,以便我可以修改它?

std::get 返回一个拷贝。

最佳答案

与您在 OP 中所说的相反,std::get 返回一个引用。事实上,它甚至有一个返回 T&&tuple&& 重载。您的误解可能源于您在导致复制的表达式中使用它。一个值得注意的例子是 auto,它被设计为默认不声明引用。看看下面的代码。

std::tuple<int, int> my_tuple;

// Declare an int whose value is copied from the first member of the tuple
auto my_int = get<0>(my_tuple);

// Get a reference to it instead
auto& my_int_ref = std::get<0>(my_tuple);
my_int_ref = 0;    // Assign 0 to the first element

// Direct use inside an expression also works.
std::get<0>(my_tuple) = 1;    // Assign 1 to the first element.

关于c++ - 获取对元组元素的引用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49397295/

相关文章:

c++ - Cmake 和 ninja 重建不必要的文件

c++ - 提升 asio 错误 10054

java - 在 Java 中传递和编辑原始对象

c++ - 通用/多态迭代器

c# - 在 C# 应用程序中导出 C++ 函数

c++ - 特征库selfadjointView问题

c# - 将 System.Web 引用添加到 Windows 10 通用应用程序

具有内存位置的 C++ 删除运算符

c++ - std::map 是否自动平衡自身

c++ - 为什么libcxx的condition_variable是constexpr和noexcept,但在标准中不是?