'Recursive std::tie in C++ [duplicate]
I've been coding in C++ for a long time and recently come across tying for pairs. Please can someone explain why the following code doesn't work or suggest an equivalent replacement?
pair<int,pair<int,int>> x = {10,{3,5}};
int w, u, v;
tie(w,tie(u,v)) = x;
I can get around it with this:
w = x.ff;
tie(u,v) = x.ss;
It just doesn't feel as nice. Many thanks
Solution 1:[1]
Because std::tie takes lvalue references, and since nested std::tie returns a prvalue of a tuple, you cannot bind an rvalue to an lvalue reference.
Try this
std::pair<int,std::pair<int,int>> x = {10,{3,5}};
int w, u, v;
auto t = std::tie(u,v);
std::tie(w, t) = x;
Solution 2:[2]
I think it may be because we can only write lvalue as an argument inside the tie. For more information you can check: http://www.cplusplus.com/reference/tuple/tie/
Solution 3:[3]
As mentioned in this post (can we do deep tie with a c++1y std::tie() -like function?) I can do this:
forward_as_tuple(w,tie(u,v)) = x;
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | 康桓瑋 |
| Solution 2 | kadircan |
| Solution 3 | George Ogden |
