For example, let's say I have a function swap as follows:
class A {
// all member variables and member functions are defined.
// Given that A deleted both copy constructor and
// overloaded assignment operator for some trivial reasons
A(const A&) = delete;
A& operator=(const A &) = delete;
};
template<typename T>
void swap (T &a, T &b) {
T temp;
temp = a;
a = b;
b = temp;
}
Now I want swap() to work for all types other than objects of type A, this is because as I have some trivial reasons for which A have not implemented overloaded assignment operator or copy constructors.
For such cases can we write some assertion or exception handling so that we should get an error when swap() function is used for objects of type A.
If we can do this in both compile time and run time, please do state the both, it will help me understanding more.
You don't have to do anything. You'll get a compile-time error if you try to use this function with a non-copyable type.
Note that std::swap already exists, and does the same thing but better.
What you can do is make your function SFINAE-friendly, aka allow templates to test if your function is callable with specific types, without causing a compilation error on test failure:
template <typename T>
requires std::is_move_constructible_v<T> && std::is_move_assignable_v<T>
void my_swap(T &a, T &b)
{
T temp(std::move(a));
a = std::move(b);
b = std::move(temp);
}
Note that I've also switched to std::move to avoid unnecessary copies.
Now requires(A a){my_swap(a, a);} will return false instead of causing a compilation error, indicating that my_swap doesn't work on A.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With