Home >Backend Development >C++ >Why does a string literal trigger the `bool` overload in function overloading?

Why does a string literal trigger the `bool` overload in function overloading?

Patricia Arquette
Patricia ArquetteOriginal
2024-11-02 13:47:30370browse

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!

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