I am trying to write a C++ class that has some overloaded methods:
class Output
{
public:
static void Print(bool value)
{
std::cout << value ? "True" : "False";
}
static void Print(std::string value)
{
std::cout << value;
}
};
Now lets say I call the method as follows:
Output::Print("Hello World");
this is the result
True
So, why, when I have defined that the method can accept boolean and string, does it use the boolean overload when I pass in a non-boolean value?
EDIT: I come from a C#/Java environment, so quite new to C++!
"Hello World"is a string literal of type “array of 12const char” which can be converted to a “pointer toconst char” which can in turn be converted to abool. That’s precisely what is happening. The compiler prefers this to usingstd::string‘s conversion constructor.A conversion sequence involving a conversion constructor is known as a user-defined conversion sequence. The conversion from
"Hello World"to aboolis a standard conversion sequence. The standard states that a standard conversion sequence is always better than a user-defined conversion sequence (§13.3.3.2/2):This “better conversion sequence” analysis is done for each argument of each viable function (and you only have one argument) and the better function is chosen by overload resolution.
If you want to make sure the
std::stringversion is called, you need to give it anstd::string: