Re: operator << for std::string in #define
  Home FAQ Contact Sign in
comp.lang.c++.moderated only
 
Advanced search
POPULAR GROUPS

more...

 Up
Re: operator << for std::string in #define         

Group: comp.lang.c++.moderated · Group Profile
Author: Ulrich Eckhardt
Date: May 8, 2007 10:10

probstm@gmail.com wrote:
> static void message ( std::string aHeader,
> std::string aMessage,
> int aTimeout = 0,
> MessageType aFlag = MSG_Information );
>
> I then use a set of defines, e.g.:
>
> #define USR_MSG( msg ) MSG::message( "", msg, 0, MSG_User )
>
> The problem is now that I get a compiler error when I write
>
> USR_MSG("The value of x is " << x);

You would always get a compile error when you write

"x is " << x

in a context where that is evaluated as is. FYI: in the context of

std::cout << "x is " << x << std::endl;

the expressions are evaluated as

(((std::cout << "x is ") << x) << std::endl);

i.e. 'x' is streamed into the result of streaming "x is " into std::cout.
Now, the result of the first streaming operation is a reference to the
stream, so the second operation also streams into the same stream. This is
called 'chaining' and can be used in other contexts, too.

It is by no means evaluated like this:

std::cout << ("x is " << x << std::endl);
> Does anybody have a smart solution for that?

No, sorry (and I wouldn't call it a problem that needs a solution). What you
might want to do is get rid of the macro now (they're evil!) and then take
a look at e.g. Boost.Format, at least for inspiration.
> I thought about rerouting std::cout but it doesn't seem to be the
> best way to me.

Do it the other way 'round:

std::ostream dbg(0);
if(debug_flag)
dbg.rdbuf( std::cout.rdbuf());
dbg << "okie-dokie!";

Optionally use a function that takes something like your MSG_User and then
return a reference to its logging target depending on that.

Uli

--
Sator Laser GmbH
Gesch
no comments
diggit! del.icio.us! reddit!