gpt4 book ai didi

c++ - 为什么 make_optional 不适用于文件流?

转载 作者:行者123 更新时间:2023-12-01 13:15:50 25 4
gpt4 key购买 nike

我正在尝试 C++17 optional 类型,并认为使用它的合适位置是一个尝试打开文件并可能返回打开文件的函数。我写的函数是这样的:

std::optional<std::fstream> openFile(std::string path)
{
std::fstream file;
file.open(path);
if (!file.is_open())
{
std::cerr << "couldn't open file" << path << std::endl;
return {};
}
else
{
return std::make_optional(file); // results in compilation error
}
}
但是,当我尝试使用 g++ 以 -std=c++17 作为参数之一进行编译时,我得到了一大堆模板编译错误消息,从以下内容开始:
In file included from read_file.cpp:3:0:
/usr/include/c++/7/optional: In instantiation of ‘constexpr std::optional<typename std::decay<_Tp>::type> std::make_optional(_Tp&&) [with _Tp = std::basic_fstream<char>&; typename std::decay<_Tp>::type = std::basic_fstream<char>]’:
read_file.cpp:16:39: required from here
/usr/include/c++/7/optional:991:62: error: no matching function for call to ‘std::optional<std::basic_fstream<char> >::optional(<brace-enclosed initializer list>)’
{ return optional<decay_t<_Tp>> { std::forward<_Tp>(__t) }; }
为什么看起来好像 fstream 不能与 std::optional 一起使用?我是否以错误的方式接近这个?如果 optional 不支持流类型,那不限制可以应用类型的位置吗?

最佳答案

当您将其传递给 make_optional 时,您的代码将尝试复制流。流无法复制,因此,您需要移动它,即

return std::make_optional(std::move(file));
或者干脆
return file;
(根据编译器的年龄,后者可能不起作用。)

关于c++ - 为什么 make_optional 不适用于文件流?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62734559/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com