代码之家  ›  专栏  ›  技术社区  ›  Dark Sorrow

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

  •  0
  • Dark Sorrow  · 技术社区  · 6 年前

    从学术角度来看,如果我想返回std::nullopt作为非常量引用。我该怎么做呢。

    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

    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;
    }
    
    0 回复  |  直到 6 年前
        1
  •  6
  •   Caleth    6 年前

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

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

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