在下面的代码中,我有两个版本的类 A
实例化后,绑定(bind)到int
另一个为int&
.
方法forward
有const
在其参数中,所以 int&
版本应该有参数 const int& t
.
右值可以用作 const T&
但是,编译器提示将非常量左值绑定(bind)到右值。
我有const
在代码中,那么为什么它不起作用?
#include <iostream>
using namespace std;
template <typename T>
class A
{
public:
T forward(const T t)
{
return t;
}
};
int main()
{
A<int> a;
A<int&> al;
int i = 1;
cout << a.forward(1) << endl; //ok
cout << al.forward(i) << endl; //ok
cout << al.forward(1) << endl; //error: non-const lvalue reference to type 'int' cannot bind to a temporary of type 'int'
return 0;
}
当我添加这些代码或替换 A<int&>
时,错误消失了与 A<const int&>
.
template <typename T>
class A<T&>
{
public:
T& forward(const T& t)
{
return t;
}
};
但我不明白为什么。
最佳答案
在 C++ 中,引用不能被const 限定。这意味着您尝试将顶级常量添加到 int&
不起作用(即被忽略)。
这本质上意味着 A<int&>::forward
的参数类型为int&
它只能绑定(bind)到左值。
关于c++ - 当 T 是左值引用时,模板类方法 f(const T) 不接受右值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/77346517/