【问题标题】:What is the difference between auto and decltype(auto) when returning from a function?从函数返回时 auto 和 decltype(auto) 有什么区别?
【发布时间】:2014-02-17 14:21:24
【问题描述】:

我很少看到decltype(auto),但是当我看到它时让我感到困惑,因为它似乎在从函数返回时与auto 做同样的事情。

auto g() { return expr; }
decltype(auto) g() { return expr; }

这两种语法有什么区别?

【问题讨论】:

    标签: c++ c++14


    【解决方案1】:

    auto遵循模板实参推演规则,始终为对象类型; decltype(auto) 遵循decltype 基于值类别推导引用类型的规则。所以如果我们有

    int x;
    int && f();
    

    然后

    expression    auto       decltype(auto)
    ----------------------------------------
    10            int        int
    x             int        int
    (x)           int        int &
    f()           int        int &&
    

    【讨论】:

    • @templateboy:不,后者只是int。只有 xvalues 成为右值引用。
    • @templateboy:如果你只是声明一个变量,auto 会更有用(例如,如果你有 auto && 用于通用参考)。 decltype 在您主要想使用 types (而不是变量)进行操作时很有用,例如在检查某些表达式是否具有某种类型的特征中。
    • @templateboy:是的,它始终是表达式的类型,可能添加了引用。如果表达式是 CV 限定值,则保留该值。详见 7.1.6.2/4([dcl.type.simple])。
    • 如果 f() 返回一个 int。 decltype((f(x))) 会返回 int && 吗?
    • @soandos:不,应该是int。只有 xvalues 而不是 prvalues 成为右值引用。
    【解决方案2】:

    auto 返回您将return 子句分配给auto 变量的值类型。 decltype(auto) 返回如果您将 return 子句包装在 decltype 中会得到什么类型。

    auto 按值返回,decltype 可能不是。

    【讨论】:

      猜你喜欢
      • 2021-11-18
      • 2017-03-18
      • 2017-08-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-07-31
      相关资源
      最近更新 更多