Home >Backend Development >C++ >Why does a string literal trigger the `bool` overload in function overloading?
String Literal Ambiguity in Function Overloading with bool
When defining overloaded methods that accept both bool and std::string arguments, developers may encounter unexpected behavior when providing string literals. Instead of invoking the std::string overload, the bool overload is prioritized.
To understand this behavior, consider the following situation:
<code class="cpp">class Output { public: static void Print(bool value) { std::cout << value ? "True" : "False"; } static void Print(std::string value) { std::cout << value; } }; Output::Print("Hello World");</code>
Despite providing a string literal, the Print() method with the bool overload is invoked. This is because string literals in C can be implicitly converted to bool values. Specifically, "Hello World" is a const char* array that can be interpreted as a pointer to a const char, which in turn can be implicitly converted to a bool. This conversion is considered a standard conversion sequence.
C prioritizes standard conversion sequences over user-defined conversions (e.g., the conversion from std::string to bool). According to the C standard (§13.3.3.2/2), a standard conversion sequence is always considered a better conversion sequence.
This behavior can be altered by explicitly providing an std::string argument to the Print() method:
<code class="cpp">Output::Print(std::string("Hello World"));</code>
The above is the detailed content of Why does a string literal trigger the `bool` overload in function overloading?. For more information, please follow other related articles on the PHP Chinese website!