Return std::nullopt 作为非常量引用

Return std::nullopt as a non-constant reference

表格学术观点,如果我想return std::nullopt作为非常参考。我将如何做同样的事情。

背景知识很少,今天我在编写代码 returning 一个 std::optional> 参考时,但我忘记将 return 设置为常量,结果出现错误。

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

只是想知道如果有人想 return 使用 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 也不是),它是一个隐式转换为该类型的对象。

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

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