Home  >  Article  >  Backend Development  >  Why does a string literal call a `bool` overload instead of a `std::string` overload in C ?

Why does a string literal call a `bool` overload instead of a `std::string` overload in C ?

Patricia Arquette
Patricia ArquetteOriginal
2024-11-04 10:12:01788browse

Why does a string literal call a `bool` overload instead of a `std::string` overload in C  ?

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn