#include #include void Print(bool P){ std::cout << P;}void Print(const std::string& P){ std::cout << P;}int main(){ Print("test\n"); const std::string Tmp = "test\n"; Print(Tmp); return 0;}
What do you think this will output? I thought the output would be:
testtest
But the output (in both VC7.1 and VC8.0) is:
1test
In VS2005 the code compiles without a single error on the highest warning level (4). I did some debugging and figured out the bool overload was called with the first function call, and the std::string overload was called with the second function call. First when I tried to code in VS2003 I found the error, I got the warning:
\Main.cpp(15) : warning C4800: 'const char *' : forcing value to bool 'true' or 'false' (performance warning)
Then it quickly became clear that I was passing a const char*, I thought it would be converted to a std::string, but since a const char* is just a pointer it was converted to a boolean, true in this case because the address wasn't 0.
I fixed it by adding an overload taking const char*. So this is what happens when you think of const char* as a string, not a pointer and when you assume "test" is more likely to be converted to a string than a boolean value.
The alternative (which is useful for a different class of problems) is to store all string literals in a centralized area, like a string table resource or a header file. Then define a unified interface to accessing them, and use that instead of inlined hardcode strings. I started doing that mainly for localization purposes, but it proves handy in other areas as well.