Parallel assignment in C++

前端 未结 6 920
醉酒成梦
醉酒成梦 2021-01-18 13:53

Is there any way of doing parallel assignment in C++? Currently, the below compiles (with warnings)

#include  

int main() { 
  int a = 4;
           


        
6条回答
  •  甜味超标
    2021-01-18 14:10

    This question is very old – I just stumbled into it today...
    ...and wondered why nobody gave this answer before...

    I think, it's possible to do it in C++11 similar like Python does it (under the hood):

    #include 
    using namespace std;
    
    int main()
    {
      int a = 4, b = 5;
      cout << "Before assignment: a: " << a << ", b: " << b << endl;
      pair ba(b, a);
      ba = make_pair(a, b); // <===: (b, a) = (a, b)
      cout << "After assignment : a: " << a << ", b: " << b << endl;
      return 0;
    }
    

    I tried this out on ideone.com. The output was:

    Before assignment: a: 4, b: 5
    After assignment : a: 5, b: 4
    

    If I remember right (I'm not a Python expert), in Python, a, b denotes a pair. (Python Doc.: 5.3. Tuples and Sequences)

    Such pair can be done in C++ 11 easily e.g. with std::pair. In this case, I made a pair of references and assigned the pair of values. It works as the make_pair() loads both variables before the right pair (of values) is assigned to the left pair of references.

    Scrolling again, I realize that this answer is close to the boost based solution of Johannes answer.

    May be, the reason is that it didn't work in C++03. I tried in coliru.stacked-crooked.com: With -std=c++03 it yields terrible to read compiler errors – changing to -std=c++11 and it compiles and executes fine as described above.

    Disclaimer

    I just cannot imagine what this solution is good for nor what practical worth it may have. This is not what I tried to do. As many other answers states "It does not work." IMHO it does (spelling it right according to the C++ language)...

提交回复
热议问题