将std :: nullopt作为非常量引用返回

问题描述 投票:-1回答: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 Studio 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;
}
c++ std c++17 stdoptional
1个回答
6
投票

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

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

我不确定你应该返回对可选项的引用,而是“可选引用”。 std::optional<std::vector<int> &>不是一个有效的类型,但std::vector<int> *std::optional<std::reference_wrapper<std::vector<int>>>都是,他们模型“可选参考”。

© www.soinside.com 2019 - 2024. All rights reserved.