I have currently a function
int myfun(const int a) {
...
return rval;
}
that performs several actions.
I mean to adapt it to write debug information on its behaviour or not according to some parameter that I can pass.
In the cases I want to write that info, I also want to pass the ofstream
to use.
And I want applications that were using myfun
to still work with no modifications.
So I would ideally change to
int myfun(const int a, ofstream & ofs) {
...
if (!(ofs == NULL)) {
ofs << ...
}
...
if (!(ofs == NULL)) {
ofs << ...
}
return rval;
}
with a default value similar to &ofs=NULL
. I know NULL
is not appropriate.
What is an appropriate way of handling this?
Note 1: I could pass an optional parameter with the output file name, but that is less flexible.
Note 2: I could also change to
int myfun(const int a, const bool debug_info, ofstream & ofs) {
...
if (debug_info) {
ofs << ...
}
with a default value debug_info=false
.
I guess this still requires a default value for ofs
as above.
Note 3:
The accepted answer in Default ofstream class argument in function proposes an overload without the ofs
parameter.
In my case that may not work, as I mean to not write anything when "ofs=NULL
".
Note 4:
This other answer apparently works, but it seems somewhat contrived to me, and I am not sure it provides all the same functionality as with passing an ofs
.
Related:
Is there a null std::ostream implementation in C++ or libraries?