int rno; string name; int marks;
tuple <int, string, int> x=make_tuple(1, "anukul", 100);
tie(rno, name, marks)=x;
This piece of code assigns the values in tuple x to the variables. In a way, it unpacks the tuple x.
So why is the function called 'tie'? What does it tie?
cplusplus states that it "Ties arguments to tuple elements". But a change in tuple elements does not reflect in the variables.
You should read the documentation for std::tie
Creates a tuple of lvalue references to its arguments [...]
so in addition to using it to "unpack" a tuple into variables as you did, you can also use it as follows
int rno = 10; string name; int marks;
tuple <int&, string&, int&> x = tie(rno, name, marks);
get<0>(x) = 42;
cout << rno; // 42
Example
I wouldn't deem the code above to be 'unpacking' anything, but rather tying the variables together with a tuple of lvalue references.
As utnapistim suggested (and the documentation shows in the sample code) another possible use unrelated from 'unpacking' is in memberwise comparisons
struct comparable {
int a, b;
bool operator==(const comparable& x) {
return std::tie(a, b) == std::tie(x.a, x,b);
}
};
It ties the names rho, name, and marks in the assignment statement so that they behave like a tuple (can be assigned to as a single entity). It refers to what it does (tie several entities into a tuple), not what you do with the result (usually unpack another tuple).
Don't forget what std::tie actually returns—a tuple. So you tie the variables together into a temporary tuple, and then assign x into that temporary tuple. Since the temporary tuple is a tuple of references, the assignment writes through to the variables which were tied into that temporary tuple.
No.
While you have a reasonable argument that you are untying x, you are not operating on x at the place where you've written std::tie.
You are instead operating on rno, name and marks, which are being tied together for the assignment.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With