I have the following code:
#include <iostream>
#include <string>
void foo(bool a)
{
std::cout << "bool" << std::endl;
}
void foo(long long int a)
{
std::cout << "long long int" << std::endl;
}
void foo(const std::string& a)
{
std::cout << "string" << std::endl;
}
int main(int argc, char* args[])
{
foo("1");
return 0;
}
When executing I get this output:
bool
I would have expected as output:
string
Why does g++ 4.9 implicitly cast this string to bool?
Your compiler is interpreting the standard correctly. Yes, this is a tricky corner case that many interviewers ask so they appear smarter than they really are.
The route
const char[2]
(the formal type of the literal"1"
) toconst char*
tobool
is a standard conversion sequence, since it uses exclusively built-in types.Your compiler must favour that to a user-defined conversion sequence, viz. the
std::string
constructor from aconst char*
.The presence of the overload
void foo(long long int a)
is a red herring.You can rather elegantly work around this in C++11 by dropping your overload to
bool
, and writingin its place. The compiler will then favour the
std::string
forconst char[N]
over the template (as that is one of the requirements of overload resolution). Nice!