制作 class 模板 std::is_swappable

Make a class template std::is_swappable

我正在尝试使 class 模板可交换。我不明白为什么静态断言失败:

#include <type_traits>

template <class T>
struct A {};

template <class T, class U>
constexpr void
swap (A <T>&, A <U>&) {}

static_assert (std::is_swappable_v <A <int>>);

int main (){}

通过

template <class T>
constexpr void
swap (A<T>&, A<T>&) {}

但是第一个不应该也可以吗?

神箭:https://godbolt.org/z/vbWWxrec4

std::is_swappable(和 std::is_swappable_with)也考虑 std::swap

... are both well-formed in unevaluated context after using std::swap;

那么对于第一种情况,swap的调用在用户定义的swapstd::swap之间存在歧义。对于第二个,用户定义的 swap 在重载解析中获胜,然后 std::is_swappable 按预期工作。