提问者:小点点

C++20概念:int not swappable_with int


我正在试用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;
}

共2个答案

匿名用户

std::swappable_with检查是否可以使用参数std::declval()std::declval()调用swap(在使用std::swap;之后)。 当tuint时,这两个参数都是rvalue,不能绑定到std::swap参数,因为这些参数是(非常量)lvalue引用。

您会奇怪int不能与int交换--没错,您不能编写std::swap(1,-1);

匿名用户

使用std::swappable_with-swappable with关心值类别,通过引用编码以及类型。

您实际上是在询问是否可以交换int类型的r值。 它说“不”; 无法交换到rvalueints。

这可能会让人困惑,但如果您这样做:

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中。

请注意,如果rvalues类型的对象是swappable_with,则上述允许交换rvalues。

相关问题


MySQL Query : SELECT * FROM v9_ask_question WHERE 1=1 AND question regexp '(c++20|概念|int|swappable_with|int)' ORDER BY qid DESC LIMIT 20
MySQL Error : Got error 'repetition-operator operand invalid' from regexp
MySQL Errno : 1139
Message : Got error 'repetition-operator operand invalid' from regexp
Need Help?