标准::移动,标准::前进,值类型和模板扣除
std::move, std::forward, value type and template deduction
假设我有这段代码
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);
格式不正确。
相关文章:
- 安全到标准:移动会员?
- 移动后是否需要重置标准::列表?
- 返回标准::移动(m_field)还是返回m_field?
- 视觉理解移动C++标准的语义
- 从标准容器中移动元素是否合法?
- 将旧版C++标准库从GNU版本移动到LLVM版本中的版本
- 标准::移动"in-place operation"
- 在C++标准中移动概念
- 标准是否保证在移动std::p ackaged_task后安全使用std::future?
- 为什么标准在移动分配运算符中使用交换?
- 无法移动标准::任何
- 标准::atomic_应该如何...<std::shared_ptr>用于线程安全类的复制和移动操作?
- C++标准::移动指针
- Visual Studio 2012 是否正确执行此操作?标准::移动
- 复制与标准::移动整数
- 标准::移动和映射分配
- C++11 GCC 4.6.2标准::移动
- 什么时候是标准::移动冗余
- 标准::移动 - 标准::内部指针
- 标准::移动,标准::前进,值类型和模板扣除