字符串文字匹配bool重载,而不是std::String

String literal matches bool overload instead of std::string

本文关键字:std String 文字 bool 重载 字符串      更新时间:2023-10-16

我正在尝试编写一个C++类,它有一些重载方法:

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");

这是的结果

真实

那么,为什么当我定义了该方法可以接受布尔值和字符串时,当我传入非布尔值时,它会使用布尔重载呢?

编辑:我来自一个C#/Java环境,所以对C++来说是全新的

"Hello World"是一个类型为"array of 12 const char"的字符串文字,它可以转换为"指向const char的指针",然后再转换为bool。这正是正在发生的事情。编译器更喜欢使用std::string的转换构造函数。

涉及转换构造函数的转换序列称为用户定义的转换序列。从"Hello World"bool的转换是标准转换序列。标准规定,标准转换序列总是优于用户定义的转换序列(§13.3.3.2/2):

标准转换序列(13.3.3.1.1)是比用户定义的转换序列或省略号转换序列更好的转换序列

这种"更好的转换序列"分析是针对每个可行函数的每个参数(并且只有一个参数)进行的,并且通过重载解析来选择更好的函数。

如果你想确保调用std::string版本,你需要给它一个std::string:

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

不确定为什么没有人发布这篇文章,但您可以添加另一个重载,将const char*转换为std::string。这使呼叫者不必为此担心。

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));
    }
};

FWIW,如果您不想为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 << "booln";
}
void foo(const std::string&)
{
  std::cerr << "stringn";  
}
int main()
{
  foo("bar");
  foo(false);
}

由于C++14,我们有来自std::string_literals命名空间的operator""s,它可以用来告诉编译器绑定到string(或C++17中的string_view)重载:

using namespace std::string_literals;
Output::Print("Hello World"s);

打印:Hello World