c++ - How to pass multi string with "<<" operator without using Macro preprocessor -
in order support logging string <<
operator, used macro handle it.
my_log_fun("hello"<<"world") //in real case, people can pass variables
and macro like
#define my_log_fun(out) \ ostringstream os; \ os << out; \ play_with(os) \
while macros give limitation continues task, there way make my_log_fun
in real function can receive parameter "hello"<<msg<<"world"
?
"is there way make my_log_fun in real function can receive parameter
<< "hello"<<msg<<"world"
?"
yes there is. instead of using macro, i'd recommend use class , overloaded global operator specialized this:
class mylogger { public: mylogger(std::ostream& logstream) : logstream_(logstream) {} template<typename t> friend mylogger& operator<<(mylogger&, const t&); private: std::ostream& logstream_; }; template<typename t> mylogger& operator<<(mylogger& log, const t& value) { log.logstream_ << value; return log; }
and use it:
int main() { mylogger log(std::cout); log << "hello" << " world!"; }
see working demo.
note:
you'll need write/delegate own stream i/o manipulator functors (like e.g. std::endl
) them working mylogger& operator<<(mylogger&, t)
operator overload.
Comments
Post a Comment