与 is_swappable_with_v 的差异

Discrepancy with is_swappable_with_v

这是 的跟进。使用 std::swappable_with_v 而不是 std::swappable_v 的代码稍作修改会产生不一致的结果:

#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);
}

静态断言仅通过 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 备注:

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.

但反过来不应该发生,即当在 using std::swap 之后对 swap 的调用成功时,特征应该产生 true.

gcc 和 clang 拒绝断言是错误的吗?

Gcc 和 clang 是正确的。从 std::is_swappable_with,

的行为

If the expressions swap(std::declval<T>(), std::declval<U>()) and swap(std::declval<U>(), std::declval<T>()) are both well-formed in unevaluated context after using std::swap;

T 是非左值引用类型时,

std::declval<T>() 产生右值表达式,它不应该被用户定义的 swap 接受(它接受左值引用) 和 std::swap(仅接受相同类型),静态断言应该失败。

您应该将模板参数指定为左值引用:

static_assert (std::is_swappable_with_v <A <int>&,A<double>&>);

顺便说一句:这也是 std::is_swappable 的做法。

provides a member constant value equal to std::is_swappable_with<T&, T&>::value