Top*_*ort 15 c++ c++-concepts c++20
我正在尝试 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;
}
Run Code Online (Sandbox Code Playgroud)
Dan*_*ica 12
std::swappable_with<T, U>检查是否swap可以using std::swap;使用参数std::declval<T>()和调用(之后)std::declval<U>()。用T和U为int,两个参数都是右值,这是不能被绑定到std::swap参数,因为这些(非const)左值的引用。
你想知道int不能与 交换int- 是的,你不能写std::swap(1, -1);.
使用std::swappable_with<T&,U&>- 可交换,关心值类别,通过引用编码,以及类型。
您实际上是在询问是否int可以交换类型的右值。它说“不”;你不能交换到 rvalue 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);
}
Run Code Online (Sandbox Code Playgroud)
它变得更自然一些。在这里,我们使用转发引用,并且参数的 l/rvalue 类别分别T与 和 中的裸类型一起存储U。
请注意,如果该类型的对象swappable_with彼此相同,则上述内容可能允许交换右值。