【发布时间】:2020-07-04 21:16:27
【问题描述】:
我正在尝试 C++17 可选类型,并认为使用它的合适位置是尝试打开文件的函数,也许 返回打开的文件。我写的函数是这样的:
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 不支持流类型,那是不是限制了该类型的应用范围?
【问题讨论】:
-
第 16 行是哪一行?
-
@ecatmur
return std::make_optional(file); // results in compilation error是第 16 行。
标签: c++ templates c++17 optional filestream