我正在学习如何使用,但在将参数传递给函数时std::optional遇到问题,因为 Type 中包含 a ,这会阻止调用。std::optional<Type>std::unique_ptr
将这样的变量 ( std::optional<Type>) 传递给函数的正确方法是什么?
这是一个可以轻松重现该问题的代码片段:
\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}\nRun Code Online (Sandbox Code Playgroud)\n我在上面的代码中看到的错误: …