c++ - 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 的教程。在我的特殊情况下,该函数是一个类方法,我想返回对成员变量的引用或数组的视图。
解决方案
只是auto
永远不会成为参考。您需要decltype(auto)
,并将返回值放在括号内:
decltype(auto) myfunc()
{
if constexpr (someBool)
{
type1 &first = refToSomething;
return (first);
}
else
{
type2 second = somethingElse;
return second;
}
}
推荐阅读
- r - sparklyr下的值匹配
- r - 数据表中行子集的总和
- javascript - 创建日期会自动将一小时添加到我的输入日期
- c# - C# 异常处理:获取扩展 CustomException 的元素
- machine-learning - 为什么我收到 HTTP 404 & sub_code":"S00004 ?IBM 沃森
- wordpress - 中继器中的 Twig Wordpress 中继器
- php - 通过 youtube api 上传时重复的视频
- php - 具有唯一文件名的联系表
- c# - 从 XAML 强制 ViewModel 实例化
- android - 后台服务和作业调度程序 XMPP 聊天应用程序