I want to declare a function which writes to std::out
by default, but also optionally enables writing to another output stream, if any is provided. For example:
print_function(std::string & str,
std::ostream & out = std::cout,
std::ostream & other = nullptr) // <-- how to make it optional???
{
out << str;
if (other == something) // if optional 'other' argument is provided
{
other << str;
}
}
Setting nullprt
obviously does not work, but how can this be done?
I'd simply use function overloading, rather than default arguments
// declare the functions in a header
void print_function(std::string &str);
void print_function(std::string &str, std::ostream &ostr);
void print_function(std::string &str, std::ostream &ostr, std::ostream &other);
// and in some compilation unit, define them
#include "the_header"
void print_function(std::string &str)
{
print_function(str, std::cout);
}
void print_function(std::string &str, std::ostream &ostr)
{
// whatever
}
void print_function(std::string & str,
std::ostream &ostr,
std::ostream &other)
{
print_function(str, ostr);
other << str;
}
All three versions of these functions can do anything you like. Depending on your needs, any can be implemented using the others.
If you need to interleave logic in the three functions (e.g. statements affecting other
need to be interleaved with statements from one of the other functions) then introduce helper functions to implement the logic in separate, more granular, parts.