我正在试用C++20的概念,std::swappable_with
是未定义的(Visual Studio,使用/std:C++最新的
),或者它的约束与下面的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
检查是否可以使用参数std::declval
和std::declval()
调用swap
(在使用std::swap;之后)。 当
t
和u
是int
时,这两个参数都是rvalue,不能绑定到std::swap
参数,因为这些参数是(非常量)lvalue引用。
您会奇怪int
不能与int
交换--没错,您不能编写std::swap(1,-1);
。
使用std::swappable_with
-swappable with关心值类别,通过引用编码以及类型。
您实际上是在询问是否可以交换int
类型的r值。 它说“不”; 无法交换到rvalueint
s。
这可能会让人困惑,但如果您这样做:
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类别分别与裸类型一起存储在T
和U
中。
请注意,如果rvalues类型的对象是swappable_with
,则上述允许交换rvalues。