Home > database >  Is std::exchange specialized for atomics?
Is std::exchange specialized for atomics?

Time:06-02

std::exchange(x,y) assigns x the value y and returns the old value of x.

Is this function specialized for atomic values, i.e. will it use std::atomic_exchange? I am thinking the answer is no, in that case why not? Was it ever considered? Seems like a good idea to me.

I am using this for resetting a simple counter and was just wondering whether if I make the counter atomic sometime in the future to support threading, whether it will just work or be unsafe.

How can I write generic function where it will use atomic exchange for atomic types and ordinary exchange for ordinary types?

CodePudding user response:

How can I write generic function where it will use atomic exchange for atomic types and ordinary exchange for ordinary types?

You can detect whether obj.exchange(x) is a valid expression (which works for std::atomic) to determine whether to use member function exchange or free function std::exchange.

#include <utility>
 
template<class T, class U = T>
constexpr
T my_exchange(T& obj, U&& new_value) {
  if constexpr (requires { obj.exchange(std::forward<U>(new_value)); })
    return obj.exchange(std::forward<U>(new_value));
  else
    return std::exchange(obj, std::forward<U>(new_value));
}

Demo

  •  Tags:  
  • c
  • Related