String Literals and Bool Overload Resolution in C
In C , overloaded methods allow you to define multiple methods with the same name but different parameter types. However, finding the exact overload to execute may seem unexpected at times. Let's explore why a string literal matches a bool overload instead of a std::string overload in certain cases.
Consider the following code:
<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>
When we call Output::Print with "Hello World", we might expect it to print the string literal. However, surprisingly, it prints True. This occurs because of the implicit conversions that are happening under the hood.
In C , string literals like "Hello World" have the type "array of 12 const chars." They can be implicitly converted to a "pointer to const char," which in turn can be implicitly converted to bool. This standard conversion sequence is preferred over the user-defined conversion sequence that would convert the string literal to an std::string.
As per C standard (13.3.3.2/2), standard conversion sequences are given higher priority than user-defined conversion sequences during overload resolution. Since the conversion from the string literal to bool is a standard conversion, it takes precedence over the std::string conversion and the Print(bool) overload is selected.
To ensure that the std::string overload is called, explicitly provide an std::string value:
<code class="cpp">Output::Print(std::string("Hello World"));</code>
Understanding these implicit conversions and overload resolution rules is crucial in C to avoid confusion and ensure that the intended overload is executed.
The above is the detailed content of Why does a string literal call a `bool` overload instead of a `std::string` overload in C ?. For more information, please follow other related articles on the PHP Chinese website!