Reputation: 2113
Let's say I have a tuple containing types A
, B
and C
:
std::tuple<A,B,C> t;
How can I extract a reference to one of it's elements, a mutable reference, so that I can modify it?
std::get
returns a copy.
Upvotes: 1
Views: 892
Reputation: 3321
Contrary to what you said in the OP, std::get
returns a reference. In fact it even has an overload for tuple&&
that returns a T&&
. Your misunderstanding probably stems from the fact that you were using it in an expression that results in a copy. A notable example of this would be auto
which is designed to not declare a reference by default. Take a look at the following code.
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.
Upvotes: 4