2

How can I make an ofstream argument optional?

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

}

the compiling error with the above method signature is:

'std::ofstream& my_file' has type 'std::ostream {aka std::basic_ostream}'

I'm using mingw32.

I want this function to write to console when there is no a second parameter. I tried myriad things, but nothing works. I do not mind if I have to check the code to see if it is open, for instance:

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

any good idea?

4

1 回答 1

4

只需使用ostream

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

这不仅适用于任何流类型,fstream而且适用于cout. 以及其他流类型,例如ostringstream.

于 2013-02-11T11:16:14.003 回答