首页 > 解决方案 > 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;
}

标签: c++c++20c++-concepts

解决方案


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


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


推荐阅读