标准::移动,标准::前进,值类型和模板扣除

std::move, std::forward, value type and template deduction

本文关键字:标准 移动 前进 类型      更新时间:2023-10-16

假设我有这段代码

template <typename T> void Swap(T&& a, T&& b) {
    T tmp = std::move(a);
    a = std::move(b);
    b = std::move(tmp);
}
int main()
{
    int a = 2;
    int b = 3;
}

根据我对这个演讲的理解,在调用Swap(a, b)时,编译器应该推断出T&&应该T&的事实并对其进行转换。但是在这种情况下,GCC给了我以下错误:

error: invalid initialization of non-const reference of type 'int&' from an rvalue of type 'std::remove_reference<int&>::type {aka int}' 
T tmp = std::move(a);

我要么必须使用 Swap(std::forward<int>(a), std::forward<int>(b))Swap(std::move(a), std::move(b)) 调用Swap,要么用 Swap(T& a, T& b) 替换Swap签名。

为什么会这样呢?这里的正确用法是什么?

你需要这个:

template <typename T> void Swap(T&& a, T&& b)
{
    using U = typename std::remove_reference<T>::type;
    U tmp = std::move(a);
    a = std::move(b);
    b = std::move(tmp);
}

正如您在问题中暗示的那样,在您的示例中,T被推导为 int& ,并且初始化int& tmp = std::move(a);格式不正确。