gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 18:32:38 25 4
gpt4 key购买 nike

当编写具有 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com