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

Well …No. Let the code speak. You want left to become right and right to become left, right?
1 |
auto left = "LEFT", right = "RIGHT" ; |
Naturally, you would use something called perhaps exchange, would you? (hint: std:swap
is taken)
1 |
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.
1 2 |
// 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
1 |
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.
1 2 3 4 5 6 7 8 |
// 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:
1 2 3 |
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.
