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

问题描述 投票:0回答:1

在下面的代码中,我实例化了两个版本的

A
类,一个绑定到
int
,另一个绑定到
int&

方法

forward
的参数中有
const
,因此
int&
版本应该有参数
const int& t

右值可以用作

const T&
,但是,编译器会抱怨将非常量左值绑定到右值。

我的代码中有

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++ templates c++20 lvalue
1个回答
0
投票

在 C++ 中,引用不能被const 限定。这意味着您尝试将 top-level const 添加到

int&
不起作用(即被忽略)。

这本质上意味着

A<int&>::forward
的参数是
int&
类型,只能绑定到左值。

© www.soinside.com 2019 - 2024. All rights reserved.