字符串匹配布尔超载来代替std :: string的 [英] String literal matches bool overload instead of std::string

查看:179
本文介绍了字符串匹配布尔超载来代替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是一个字符串类型12阵列的为const char ,它可以被转换为一个指针为const char ,这又可以转化为布尔。这是precisely发生了什么。编译器prefers此使用的std ::字符串的转换构造。

"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布尔标准转换序列转换的。该标准规定,标准转换序列总是比一个用户定义的转换序列(§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 ::字符串版本叫做,你需要给它一个的std ::字符串

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

这篇关于字符串匹配布尔超载来代替std :: string的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆