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?
Just use ostream
:
bool LookingFor(std::string &mi_name, std::ostream &out = std::cout) {
out << xxx;
}
This will work with any stream type, not only fstream
, but also cout
. And other stream types, like ostringstream
.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.