首页 > 解决方案 > C++ - 自动返回引用和非引用类型

问题描述

在编写具有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++referenceautorvaluelvalue

解决方案


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

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

推荐阅读