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?

1 Answer 1

4

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.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.