'+' : cannot add two pointers (LPTSTR + tstring)

 
WriteLog(ess.lpServiceName + _T(": stopped."));

error C2110: '+' : cannot add two pointers

how can i print servicename and text correctly to my log? (my writelog takes tstring)

Last edited on
One way to do it is:

WriteLog( (std::string(ess.lpServiceName) + ": stopped.").c_str() );

You are converting the strings to std::string first, add them and then convert back to a char array.

If you are using wide character strings, it would look like
WriteLog( (std::wstring(ess.lpServiceName) + L": stopped.").c_str() );


If you have two compile-time-constant strings, it's even easier. Just don't write the +
WriteLog( "foo" "bar" );

(That's mostly used for macros like __FILE__ )

Ciao, Imi.
Ciao,
Danke for the hint Imi!

easy-thinking: just cast it
 
WriteLog((tstring)ess.lpServiceName + _T(": stopped."));

works for me...

- disadvantages?
- disadvantages?


Well, the only disadvantage is, that it looks crude. But its 100% syntactical the same thing ;-). The generated executable will be exactly the same.


"(foobar)23" is the same as "foobar(23)". Both are calling the constructor of foobar with 23 as parameter.


But this "casting to an class" feature is rarely used, though. The second version is recommended for classes, as usually programmer think in terms of "calling constructors" instead of "casting parameters to classes" ;-)


It even works for integral types. "(int)23.1" is actually the same as "int(23.1)".

And instead of "(char*)foo" you could write "typedef PCHAR char*; PCHAR(foo);" (the typedef is necessary, as "char*(foo)" is actually a cast to a function returning char and taking a type "foo" which is even not a type here. ;)

But hey, do your co-workers a favour and use the more common versions of "string(xxx)" for classes and "(char*)xxx" for primitive types. :-D

Ciao, Imi.
Topic archived. No new replies allowed.