小编Roh*_*ran的帖子

如何将包含 std::unique_ptr 的 std::optical 结构传递给函数?

我正在学习如何使用,但在将参数传递给函数时std::optional遇到问题,因为 Type 中包含 a ,这会阻止调用。std::optional<Type>std::unique_ptr

\n

将这样的变量 ( std::optional<Type>) 传递给函数的正确方法是什么?

\n

这是一个可以轻松重现该问题的代码片段:

\n
#include <iostream>\n#include <optional>\n#include <memory>\nusing namespace std;\n\nstruct myStruct\n{\n    std::unique_ptr<int> a;\n};\n\nint func(const myStruct& val, std::optional<myStruct> opt)\n{\n    if (opt.has_value())\n    {\n        return *(opt.value().a);\n    }\n    else \n    {\n        return *(val.a);\n    }\n}\n\nint main()\n{\n    cout << "Hello World";\n    myStruct val;\n    val.a = std::make_unique<int>(5);\n    std::optional<myStruct> opt = std::nullopt;\n    myStruct temp;\n    temp.a = std::make_unique<int>(10);\n    opt = std::move(temp);\n    std::cout << "result is " << func(val, opt) << std::endl;\n    return 0;\n}\n
Run Code Online (Sandbox Code Playgroud)\n

我在上面的代码中看到的错误: …

c++ function unique-ptr c++17 stdoptional

3
推荐指数
1
解决办法
971
查看次数

标签 统计

c++ ×1

c++17 ×1

function ×1

stdoptional ×1

unique-ptr ×1