-1

从学术角度来看,如果我想将 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;
}
4

1 回答 1

6

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

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

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

于 2019-03-19T12:06:04.303 回答