I was trying to clean up some code that uses char* with std::string and ran into a problem that is illustrated by the following code.
void Foo( int xIn , const std::string & fooIn )
{
std::cout << "string argument version called \n";
}
void Foo( int xIn , bool flagIn = true )
{
std::cout << "bool argument version called \n";
}
int main()
{
int x = 1;
Foo( x , "testing" );
return 0;
}
When I run the program I get bool argument version called. Is a char* to bool conversion preferred over char* to const std::string& or is Visual Studio 2008 playing tricks on me ?
Surprising as this behaviour is, the compiler is compliant:
char*toboolconversion is preferred over the conversion tostd::string.Read more here.
The exact rules are spelled out in the C++ standard. They’re surprisingly complicated, but the following paragraph is crucial here:
char*-to-boolrequires a “standard conversion sequence” whereaschar*-to-stringrequires a “user-defined conversion sequence”. Therefore, the former is preferred.