Home > Blockchain >  Recursive std::tie in C
Recursive std::tie in C

Time:03-20

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

CodePudding user response:

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

CodePudding user response:

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/

  • Related