This is possible, but not in a way that preserves the my_log_fun("hello"<<"world")
syntax. There are a few ways I can think of.
- Make your own stream class (probably a bad idea) or streambuf (not sure that would work).
- Change my_log_fun() to a function that simply returns the stream. I can't see how that would support your post-processing case, though.
- The C++11 approach with recursive variadic templates.
For example (untested code):
template<typename... Args> void do_my_log_fun(ostream& os, Args... args);
template<typename T> void do_my_log_fun(ostream& os, T arg) {
os << arg;
}
template<typename T, typename... Rest>
void do_my_log_fun(ostream& os, T arg1, Rest... args) {
do_my_log_fun(arg1);
do_my_log_fun(args);
}
template<typename... Args> void my_log_fun(Args... args) {
ostringstream os;
do_my_log_fun(os, args...);
play_with(os);
}
- The C approach to variadic functions. I won't go into this as it amounts to writing a function that's called like
printf
and would probably end up forwarding to sprintf
or snprintf
.
- Use a global stream or stream-like object.
It would look something like this:
enum LoggerProxy {logger};
template<typename T>
ostream operator<< (LoggerProxy lhs, T rhs) {
ostringstream os;
return os << rhs;
}
void my_log_fun(ostream& os) {
play_with(os);
}
And you would use it like this:
my_log_fun(logger<<"hello"<<"world");
Always with logger
first.