繁体   English   中英

返回std :: nullopt作为非恒定引用

[英]Return std::nullopt as a non-constant reference

如果我想返回std :: nullopt作为非恒定引用,请形成学术观点。 我将如何做同样的事情。

没什么背景,今天当我在处理返回std :: optional>引用的代码时,却忘记了使返回常量,并得到了错误。

 Error (active) E0434 a reference of type "std::optional<std::vector<std::any, std::allocator<std::any>>> &" (not const-qualified) cannot be initialized with a value of type "const std::nullopt_t" Socket.IO D:\\Hardware\\Windows\\Visual Studio\\Socket.IO\\Socket.IO\\main.cpp 46 Error C2440 'return': cannot convert from 'const std::nullopt_t' to 'std::optional<std::vector<std::any,std::allocator<_Ty>>> &' Socket.IO d:\\hardware\\windows\\visual studio\\socket.io\\socket.io\\main.cpp 46 

只是想知道是否有人想使用std :: optional返回一个非常量引用,他将如何做。

使用平台:Windows 10 Pro x64

开发环境:Visual Studios 15.9.9

std::vector<int>> a;
std::optional<std::vector<int>>& test(int b)
{
    a.clear();
    a.push_back(b);
    if(b)
         return a;
    else
         return std::nullopt;
}

std::nullopt不是std::optional<std::vector<int>> (也不是a ),它是具有一个隐式转换到该类型的对象。

您不能将非常量引用绑定到临时文件,例如转换结果。

我不确定您是否应该返回对可选的引用,而是“可选的引用”。 std::optional<std::vector<int> &>不是有效类型,但std::vector<int> *std::optional<std::reference_wrapper<std::vector<int>>>是,它们为“可选参考”建模。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM