【发布时间】:2017-12-01 17:14:49
【问题描述】:
以下代码编译失败:
#include <iostream>
using namespace std;
int add2(const int& x)
{
return x + 2;
}
template <typename T>
T add2T(T&& x) {
return add2(std::forward<T>(x));
}
int main(int argc, char** argv) {
int x = 0;
cout << "Add 2" << endl;
cout << add2(2) << endl;
cout << add2(x) << endl;
cout << "Add 2T" << endl;
cout << add2T(10) << endl;
cout << add2T(x) << endl;
return 0;
}
带有此消息:
main.cpp: In instantiation of 'T add2T(T&&) [with T = int&]':
main.cpp:26:20: required from here
main.cpp:12:16: error: cannot bind non-const lvalue reference of type 'int&' to an rvalue of type 'int'
return add2(std::forward<T>(x));
~~~~^~~~~~~~~~~~~~~~~~~~
我不确定为什么编译器会尝试将非常量左值引用绑定到右值。无论如何,前向应该衰减为左值引用,对吧?
【问题讨论】: