c++ the commitee naming — std::exchange

Naming is hard. This is largely about naming. Ditto, what might std::exchange do?

Exchange two values?

 

exchange definition from a dictionary

 

Well …No.  Let the code speak. You want left to become right and right to become left, right?

auto left = "LEFT", right = "RIGHT" ;       

Naturally, you would use something called perhaps exchange, would you? (hint: std:swap is taken)

std::exchange(left,right);

Alas. std::exchange is a name, given by a committee. Above does not exchange.

After the call above right is unchanged.  Indeed left == right, and there is a return value (for some reason) too.

// std::exchange calling by the book
auto left_previous = std::exchange(left,right);

To do the exchange by the meaning from the English language, one more call is required

auto right_previous = std::exchange(right, left_previous ) ;

Voila, left and right are exchanged!

No wonder people are looking to Rust, Go, Swift and elsewhere. In case you want to stay with C++, be brave and add this function to your library.

// exchange as the English term "exchange" defines
template<typename T>
void dbj_exchange(T & a, T & b) 
{
    T t = a;
    a = b ;
    b = t ;
}

Thinking of it all, perhaps std::exchange  is better to be called “assign”? Who knows. Back to dbj_exchange .Usage is daringly simple too:

auto left = "LEFT", right = "RIGHT" ;

dbj_exchange(left,right);

No SFINAE necessary. In case of the wrong usage, wrong types used, or any similar libertarian activity, you will be punished by the compiler, disproportionately.

None of us is smart as all of us