Parallel assignment in C++

前端 未结 6 906
醉酒成梦
醉酒成梦 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:21

    That's not possible. Your code example

    a, b = b, a;
    

    is interpreted in the following way:

    a, (b = b), a
    

    It does nothing. The comma operator makes it return the value of a (the right most operand). Because assignment binds tighter, b = b is in parens.

    The proper way doing this is just

    std::swap(a, b);
    

    Boost includes a tuple class with which you can do

    tie(a, b) = make_tuple(b, a);
    

    It internally creates a tuple of references to a and b, and then assigned to them a tuple of b and a.

提交回复
热议问题