This is a follow up of this question. A slightly modified version of the code, using std::swappable_with_v
rather than std::swappable_v
yields inconsistent results:
#include <type_traits>
template <class T>
struct A {};
template <class T, class U>
constexpr void
swap (A<T>&, A<U>&) {}
int main (){
static_assert (std::is_swappable_with_v <A <int>,A<double>>);
using std::swap;
A<int> a;
A<double> b;
swap(a,b);
}
The static assert passes only with msvc https://godbolt.org/z/G6sj86sfq. Though all 3 major compilers accept the code when the static assert is removed: https://godbolt.org/z/hbdq4Eoh1
cppreference notes:
This trait does not check anything outside the immediate context of the swap expressions: if the use of T or U would trigger template specializations, generation of implicitly-defined special member functions etc, and those have errors, the actual swap may not compile even if std::is_swappable_with<T,U>::value compiles and evaluates to true.
But the reverse should not happen, ie when a call to swap
succeeds after using std::swap
the trait should yield true
.
Are gcc and clang wrong in rejecting the assert?
Gcc and clang are correct. From the behavior of std::is_swappable_with
,
If the expressions
swap(std::declval<T>(), std::declval<U>())
andswap(std::declval<U>(), std::declval<T>())
are both well-formed in unevaluated context afterusing std::swap
;
std::declval<T>()
yields rvalue expression when T
is a non-lvalue-reference type, it shouldn't be accepted by the user-defined swap
(which accepts lvalue-references) and std::swap
(which accepts only same types), the static assert should fail.
You should specify template arguments as lvalue-reference as:
static_assert (std::is_swappable_with_v <A <int>&,A<double>&>);
BTW: This is also how std::is_swappable
does.
provides a member constant value equal to
std::is_swappable_with<T&, T&>::value