Recursive std::tie in C++

Viewed 58

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

3 Answers

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;

Demo

Related