c++ - 当 T 是左值引用时,模板类方法 f(const T) 不接受右值

标签 c++ templates c++20 lvalue

在下面的代码中,我有两个版本的类 A实例化后,绑定(bind)到int另一个为int& .

方法forwardconst在其参数中,所以 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/

相关文章:

c++ - 如何在 Openscenegraph 中从 2D 鼠标单击屏幕坐标点计算 3D 点(世界坐标)?

c++ - 如果存储被分段,则使用 If 语句在类内部创建动态数组

c++ - STL 设置自定义排序功能在 Quicy 2005 中有效,但在 MS Studio 2010 中无效

c++ - initializer_list 和 move 语义

c++ - 模板函数中的 itoa

c++ - GCC 与 Clang 关于临时绑定(bind)到另一个临时的右值引用的生命周期

c++ - 即使在宏替换后也无法解析变量

c++ - 我怎样才能创建一个行为与另一种类型一样的类型?

c++ - "With a stackless coroutine, only the top-level routine may be suspended."是什么意思

c++ - 使用范围库初始化std::vector