假设我有一个包含类型 A
、B
和 C
的元组:
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/