C++ - 自动返回引用和非引用类型

标签 c++ reference auto rvalue lvalue

当编写具有 auto 返回类型的函数时,我们可以使用 constexpr if 返回不同类型。

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

但是,我正在努力弄清楚如何仅将其中一种类型作为引用。看起来以下代码仍然返回两个分支的右值

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

有办法做到这一点吗?谷歌并没有透露太多,因为有很多关于自动和引用返回的更一般使用的教程。在我的特定情况下,该函数是一个类方法,我想返回对成员变量的引用或数组的 View 。

最佳答案

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

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

关于C++ - 自动返回引用和非引用类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69233057/

相关文章:

c++ - 如何将 CFString 转换为 HFSUniStr255?

c++ - 从函数返回的对象的延长生命周期

c++ - 为什么指向函数的指针不能绑定(bind)到左值引用,而函数可以?

c++ - 为什么 auto 不能用于重载函数?

c++ - 是否保证 sizeof(T[N]) == N * sizeof(T)?

c++ - 线程矩阵乘法

c++ - 没有匹配的初始化构造函数

c# - 在 Visual Studio 中查找引用

c# - 为什么我不能使用包含自 Action 为参数或返回类型的 DLL 中的函数?

c++ - std::function 是否比自动存储 lambda 函数重