Phi*_*erg 2 c++ reference rvalue lvalue auto
当编写具有返回类型的函数时,auto我们可以使用constexpr if返回不同的类型。
auto myfunc()
{
constexpr if (someBool)
{
type1 first = something;
return first;
}
else
{
type2 second = somethingElse;
return second;
}
}
Run Code Online (Sandbox Code Playgroud)
然而,我正在努力弄清楚如何仅将其中一种类型作为参考。看来以下代码仍然返回两个分支的右值
auto myfunc()
{
constexpr if (someBool)
{
type1 &first = refToSomething;
return first;
}
else
{
type2 second = somethingElse;
return second;
}
}
Run Code Online (Sandbox Code Playgroud)
有没有办法做到这一点?谷歌并没有透露太多,因为有很多关于自动和引用返回的更一般使用的教程。在我的特定情况下,该函数是一个类方法,我想返回对成员变量的引用或数组的视图。
只是auto永远不会成为参考。相反,您需要decltype(auto)将返回值放在括号内:
decltype(auto) myfunc()
{
if constexpr (someBool)
{
type1 &first = refToSomething;
return (first);
}
else
{
type2 second = somethingElse;
return second;
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
463 次 |
| 最近记录: |