String literal matches bool overload instead of std::string

ぃ、小莉子 提交于 2019-11-26 04:25:27

问题


I am trying to write a C++ class that has some overloaded methods:

class Output
{
public:
    static void Print(bool value)
    {
        std::cout << value ? \"True\" : \"False\";
    }

    static void Print(std::string value)
    {
        std::cout << value;
    }
};

Now lets say I call the method as follows:

Output::Print(\"Hello World\");

this is the result

True

So, why, when I have defined that the method can accept boolean and string, does it use the boolean overload when I pass in a non-boolean value?

EDIT: I come from a C#/Java environment, so quite new to C++!


回答1:


"Hello World" is a string literal of type "array of 12 const char" which can be converted to a "pointer to const char" which can in turn be converted to a bool. That's precisely what is happening. The compiler prefers this to using std::string's conversion constructor.

A conversion sequence involving a conversion constructor is known as a user-defined conversion sequence. The conversion from "Hello World" to a bool is a standard conversion sequence. The standard states that a standard conversion sequence is always better than a user-defined conversion sequence (§13.3.3.2/2):

a standard conversion sequence (13.3.3.1.1) is a better conversion sequence than a user-defined conversion sequence or an ellipsis conversion sequence

This "better conversion sequence" analysis is done for each argument of each viable function (and you only have one argument) and the better function is chosen by overload resolution.

If you want to make sure the std::string version is called, you need to give it an std::string:

Output::Print(std::string("Hello World"));



回答2:


FWIW, it can be address this way (if templates can be used), if you don't want to add overloads for const char*.

#include <iostream>
#include <string>
#include <type_traits>

template <typename Bool,
          typename T = std::enable_if_t<std::is_same<Bool, bool>{}>>
void foo(Bool)
{
  std::cerr << "bool\n";
}

void foo(const std::string&)
{
  std::cerr << "string\n";  
}

int main()
{
  foo("bar");
  foo(false);
}



回答3:


Not sure why nobody posted this, but you can add another overload that converts from const char* to std::string for you. This saves the caller from having to worry about this.

class Output
{
public:
    static void Print(bool value)
    {
        std::cout << value ? "True" : "False";
    }

    static void Print(std::string value)
    {
        std::cout << value;
    }

    // Just add the override that cast to std::string
    static void Print(const* char value)
    {
        Output::Print(std::string(value));
    }
};


来源:https://stackoverflow.com/questions/14770252/string-literal-matches-bool-overload-instead-of-stdstring

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!