C++20 概念:int 不是 swappable_with int

C++20 concepts: int not swappable_with int

我正在尝试 C++20 的概念,并且 std::swappable_with 未定义(Visual Studio,使用 /std:c++latest)或者它的约束与下面的 MCVE 不匹配( g++10 使用 -std=c++2a)——也就是说,int 不能与 int 交换(!)。解决这个问题的方法是什么?如果 int 不能与 int 交换,我看不到 任何东西 工作。

#include <concepts> 

template <typename T, typename U>
requires std::swappable_with<T,U>
void mySwap(T& t, U& u)
{
    T temp = t; t = u; u = temp;
}

int main()
{
    int x, y;
    mySwap(x, y);

    return 0;
}

使用 std::swappable_with<T&,U&> - 可交换,关心值类别、按引用编码以及类型。

您实际上是在询问 int 类型的右值是否可以交换。它说 "no";你不能换成右值 ints.

这可能会造成混淆,但如果您这样做:

template <class T, class U>
requires std::swappable_with<T,U>
void mySwap(T&& t, U&& u) {
  auto temp = std::forward<T>(t);
  t = std::forward<U>(u);
  u = std::move(temp);
}

它变得更自然了。在这里,我们使用转发引用,参数的 l/rvalue 类别与裸类型一起分别存储在 TU 中。

请注意,如果该类型的对象彼此 swappable_with,则以上内容允许交换右值。

std::swappable_with<T, U> 检查是否可以使用参数 std::declval<T>()std::declval<U>() 调用 swap(在 using std::swap; 之后)。 TUint,两个参数都是 rvalues,不能绑定到 std::swap 参数,因为它们是 (非常量)左值引用。


您想知道 int 不能与 int 交换 — 没错,您不能写 std::swap(1, -1);.