Reputation: 1165
I'd like to implement a macro which does the following:
#define report(s) print(), throw std::runtime_error(s)
print()
is a function that I always call to print some predefined stuff. s
need to support:
report("abc"); // ok
report("abc"<<100); // == report("abc100")
Apart from whatever print() outputs, Nothing else should be printed. The exception will be caught by the caller and printed there.
I find it difficult to support << in the above macro.
P.S. report() is a macro already used every where in my code base and I just want to change its behaviour. Calls like report("abc"<<100); have to be supported. define it as a function and add ';' at the end doesn't look appropriate.
Upvotes: 0
Views: 105
Reputation: 1
Perhaps the following (untested!) code might be inspirational
#define report(Log) do { std::ostringstream _os; \
_os << Log << std::flush; print(_os.str()); \
throw std::runtime(_os.str()); } while(0)
and you might use it as report("x=" << x)
;
BTW, you might even pass the source location using
#define report_at(Log,Fil,Lin) do { std::ostringstream _os; \
_os << Fil << ":" << Lin << ": " << Log << std::flush; \
print(_os.str()); \
throw std::runtime(_os.str()); } while(0)
(to lower probability of collision with _os
you might even replace all its occurrences inside the brace with _os##Lin
using preprocessor concatenation)
#define report_at_bis(Log,Fil,Lin) report_at(Log,Fil,Lin)
#define report(Log) report_at_bis(Log,__FILE__,__LINE__)
and this shows one of the cases where a macro is really useful.
Upvotes: 2