c++ - C++20 概念:int not swappable_with int
问题描述
我正在尝试 C++20 的概念,要么std::swappable_with
是未定义的(Visual Studio, using /std:c++latest
),要么它的约束与下面的 MCVE 不匹配(g++10 using -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>
检查是否swap
可以using std::swap;
使用参数std::declval<T>()
和. 调用(之后) std::declval<U>()
。WithT
和U
being int
,两个参数都是rvalues,不能绑定到std::swap
参数,因为它们是(非常量)左值引用。
你想知道int
不能交换int
——没错,你不能写std::swap(1, -1);
.
推荐阅读
- apache-kafka - 在 ReactiveKafkaProducerTemplate 发送方法中模拟 SenderResult
- visual-studio-code - 在 Windows 资源管理器中打开目录的链接
- php - Laravel Livewire 仅将整个模型或所需数据作为变量传递
- javascript - new Date() 不返回区域
- reactjs - 使用 apache 反向代理创建-react-app
- amazon-ec2 - 无法使用 netcat 侦听 aws ec2 实例中的端口
- express - Stripe 是否仍允许预填充快递账户?如果是,传递电子邮件、名字、公司名称等内容的语法是什么
- azure - 创建 SQL 数据库时错误验证失败
- docker - docker-compose 运行任何命令都会出错
- django - ValueError:要解压的值太多(预期为 2)Django