I want to achieve something like this:
#include <iostream>
#include <fstream>
#include <string>
void write(std::ofstream& o)
{
o << "Some text..." << std::endl;
}
int main(const int argc, const char** argv)
{
if (argc == 2){
auto outputStream = std::ofstream(argv[1]);
write(outputStream);
}
else{
auto outputStream = std::ofstream(std::cout);
write();
}
}
The code doesn't compile because std::ofstream
cannot be constructed from std::cout
.
A viable solution is to use rdbuf()
in the context pointer_to_ofstream->basic_ios<char>::rdbuf(std::cout.rdbuf())
(as provided in this entry).
Is there a better solution?