Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Shouldn't tie be called untie?

Tags:

c++

stl

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.

like image 904
anukul Avatar asked Sep 14 '15 10:09

anukul


3 Answers

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); 
  }
};
like image 126
Marco A. Avatar answered Nov 20 '22 09:11

Marco A.


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.

like image 7
Angew is no longer proud of SO Avatar answered Nov 20 '22 09:11

Angew is no longer proud of SO


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.

like image 3
Lightness Races in Orbit Avatar answered Nov 20 '22 10:11

Lightness Races in Orbit