字符串文字匹配 bool 重载而不是 std::string
我正在尝试编写一个具有一些重载方法的 C++ 类:
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");
这是结果
是的
那么,为什么,当我定义了该方法可以接受布尔值和字符串时,当我传入一个非布尔值时,它是否使用布尔重载?
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?
我来自 C#/Java 环境,对 C++ 很陌生!
推荐答案
"Hello World"
是一个类型为array of 12 const char
"的字符串字面量,可以转换为指向 const char
的指针",然后又可以转换为 bool
.这正是正在发生的事情.编译器更喜欢使用 std::string
的转换构造函数.
"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.
涉及转换构造函数的转换序列称为用户定义的转换序列.从 "Hello World"
到 bool
的转换是一个标准转换序列.标准规定标准转换序列始终优于用户定义的转换序列(第 13.3.3.2/2 节):
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):
标准转换序列 (13.3.3.1.1) 是比用户定义的转换序列或省略号转换序列更好的转换序列
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.
如果你想确保调用 std::string
版本,你需要给它一个 std::string
:
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"));
相关文章