【问题标题】:C++ - auto return reference and non reference typeC++ - 自动返回引用和非引用类型
【发布时间】:2021-11-12 21:36:39
【问题描述】:

在编写返回类型为auto 的函数时,我们可以使用constexpr if 来返回不同的类型。

auto myfunc()
{
   constexpr if (someBool)
   {
      type1 first = something;
      return first;
   }
   else
   {
      type2 second = somethingElse;
      return second;
   }
}

但是,我正在努力研究如何仅将其中一种类型作为参考。看起来下面的代码仍然为两个分支返回一个 r 值

auto myfunc()
{
   constexpr if (someBool)
   {
      type1 &first = refToSomething;
      return first;
   }
   else
   {
      type2 second = somethingElse;
      return second;
   }
}

有没有办法做到这一点?谷歌没有透露太多,因为有很多关于更一般地使用 auto 和 return by reference 的教程。在我的特殊情况下,该函数是一个类方法,我想返回对成员变量的引用或数组的视图。

【问题讨论】:

    标签: c++ reference auto rvalue lvalue


    【解决方案1】:

    auto 永远不会成为参考。您需要 decltype(auto) 代替,并将返回值放在括号内:

    decltype(auto) myfunc()
    {
       if constexpr (someBool)
       {
          type1 &first = refToSomething;
          return (first);
       }
       else
       {
          type2 second = somethingElse;
          return second;
       }
    }
    

    【讨论】:

      猜你喜欢
      • 2019-10-19
      • 2016-12-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-06-26
      • 2010-10-01
      • 2012-08-28
      • 1970-01-01
      相关资源
      最近更新 更多