You can make Display
a helper function of a manipulator display_msg
, a class which encapsulates the output. Display
cannot return void
, because if you are looking for the syntax os << Display()
to work, Display
will have to return something other than void
.
Here is the definition of display_msg
:
class display_msg { };
The class is left empty because it performs nothing of importance. We will overload the insertion operator for this class so that we can access the output stream and insert our custom data into:
std::ostream& operator<<(std::ostream& os, const display_msg&)
{
return os << "My message";
}
This is a very simple setup. But as you said, you would like for the output to be redirected to standard output ( std::cout
). For that you will have to copy the buffer of std::cout
to the file stream. You can do that using RAII (in order to manage lifetime dependencies between the objects):
struct copy_buf
{
public:
copy_buf(std::ios& lhs, std::ios& rhs)
: str(lhs), buf(lhs.rdbuf())
{
lhs.rdbuf(rhs.rdbuf());
}
~copy_buf() { str.rdbuf(buf); }
private:
std::ios& str;
std::streambuf* buf;
};
The inserter can use this like so:
std::ostream& operator<<(std::ostream& os, const display_msg&)
{
copy_buf copy(os, std::cout);
return os << "My message";
}
Display
is a simple helper function that returns the class:
display_msg Display()
{
return display_msg();
}
std::ifstream f("in.txt");
f << Display(); // redirects to standard output