Why does a quoted string match bool method signature before a std::string?

前端 未结 3 1123
滥情空心
滥情空心 2020-12-06 05:49

Given the following methods:

// Method 1
void add(const std::string& header, bool replace);

//Method 2
void add(const std::string& name, const std::         


        
3条回答
  •  清歌不尽
    2020-12-06 06:07

    Pointers have an implicit conversion to bool. Perhaps you have seen the following:

    void myFunc(int* a)
    {
        if (a)
            ++(*a);
    }
    

    Now, in C++, implicit conversions between built-in types take precedence over conversions between class-types. So for example, if you had a class:

    class Int
    {
    public:
        Int(int i) {}
    }
    

    And you overloaded a function for long and Int:

    void test(long n) {cout << "long";}
    void test(Int n) {cout << "Int";}
    

    You'll see that the following code calls the long overload:

    int i;
    test(i);
    

提交回复
热议问题