Home > Backend Development > C++ > Why does `Output::Print(\'Hello World\')` print \'True\' instead of \'Hello World\'?

Why does `Output::Print(\'Hello World\')` print \'True\' instead of \'Hello World\'?

Barbara Streisand
Release: 2024-11-02 06:53:02
Original
886 people have browsed it

Why does `Output::Print(

String Literal Overload Conflict: Bool vs. std::string

In C , class methods can be overloaded to accept different parameter types. However, sometimes a string literal may unexpectedly matched the boolean type overload instead of the expected std::string overload.

Problem description:

Suppose we have an Output class defined as follows:

<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;
    }
};</code>
Copy after login

When calling Output::Print("Hello World "), the output result is "True" instead of the expected "Hello World".

Problem analysis:

Although we defined the std::string overload, "Hello World" is actually a character array constant that can be implicitly converted to bool. The compiler prefers this standard conversion over the user-defined std::string conversion constructor.

According to the C standard (§13.3.3.2/2), standard conversion orders prevail over user-defined conversion orders. Therefore, the compiler chooses the bool overload because it has better conversion order.

Workaround:

In order to explicitly call the std::string overload, we need to explicitly pass "Hello World" as std::string:

<code class="cpp">Output::Print(std::string("Hello World"));</code>
Copy after login

The above is the detailed content of Why does `Output::Print(\'Hello World\')` print \'True\' instead of \'Hello World\'?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template