C++中的可选流参数

optional ofstream parameter in C++

本文关键字:参数 C++      更新时间:2023-10-16

如何使ofstream参数可选?

bool LookingFor(std::string &mi_name, ofstream &my_file = std::cout)
{
    my_file << xxx;
.......
}

上述方法签名的编译错误为:

'std::流&my_file"具有类型"std::ostream{aka std::basic_stream}"

我正在使用mingw32。

我希望这个函数在没有第二个参数的情况下写入控制台。我尝试了无数种方法,但都无济于事。我不介意是否必须检查代码以查看它是否打开,例如:

if(my_file.isopen())
    my_file << xxx;
else
    cout << xxx;

有什么好主意吗?

只需使用ostream:

bool LookingFor(std::string &mi_name, std::ostream &out = std::cout) {
    out << xxx;
}

这将适用于任何流类型,不仅适用于fstream,也适用于cout。以及其他流类型,如ostringstream