【问题标题】:Do the reference-collapsing rules apply to return type?引用折叠规则是否适用于返回类型?
【发布时间】:2019-08-08 21:06:19
【问题描述】:

std::forward 函数模板返回 T&&。因此,为了将其参数作为左值引用或右值引用转发,std::forward 的返回类型必须是:

T&& if T is a non-reference type (T && == T&&)
T& if T is an lvalue reference type (T& && == T&)

我的意思是std::forward的返回类型会因为引用折叠规则而改变还是解释不同?

std::forward 的返回类型是转发(通用)引用吗?

【问题讨论】:

    标签: c++11 rvalue-reference type-deduction forwarding-reference


    【解决方案1】:

    答案是肯定的。引用折叠规则,如[dec.ref]/6 所述,不区分变量类型、函数参数类型或函数返回类型。

    【讨论】:

    • 谢谢,但您指的是哪一种说法?您提到的子句根本没有提到返回类型......
    • @beginpluses,链接的第一段只讨论类型。它没有说明规则是否适用于变量的类型、函数参数的类型或返回类型。由此,我认为该规则适用于所有类型。
    【解决方案2】:

    这取决于上下文。如果以某种方式推断出类型(模板上下文),它将起作用:

    int a;
    template <typename T>
    T&& foo()
    {
        return a;
    }
    

    另一方面,如果不推导出类型,它将不起作用

    int a;
    int&& bar()
    {
        return static_cast<int&>(a); // error: binding l-value to r-value reference
    }
    

    就像L Shau指出的,你可以在the standard找到规则。

    【讨论】:

      猜你喜欢
      • 2018-03-27
      • 1970-01-01
      • 2013-06-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-03-12
      • 2022-03-02
      • 2015-07-07
      相关资源
      最近更新 更多