C++ addition overload ambiguity

前端 未结 5 1360
时光说笑
时光说笑 2020-12-21 13:14

I am coming up against a vexing conundrum in my code base. I can\'t quite tell why my code generates this error, but (for example) std::string does not.

cla         


        
5条回答
  •  别那么骄傲
    2020-12-21 13:59

    The reason for the ambiguity is that one candidate function is better than another candidate function only if none of its parameters are a worse match than the parameters of the other. Consider your two functions:

    friend String operator+(const String&, const char*); // (a)
    String operator+(const String&);                     // (b)
    

    You are calling operator+ with a String and a const char*.

    The second argument, of type const char*, clearly matches (a) better than (b). It is an exact match for (a), but a user-defined conversion is required for (b).

    Therefore, in order for there to be an ambiguity, the first argument must match (b) better than (a).

    The String on the left-hand side of the call to operator+ is not const. Therefore, it matches (b), which is a non-const member function, better than (a), which takes a const String&.

    Therefore, any of the following solutions would remove the ambiguity:

    • Change the member operator+ to be a const member function
    • Change the non-member operator+ to take a String& instead of a const String&
    • Call operator+ with a const String on the left hand side

    Obviously, the first, also suggested by UncleBens, is the best way to go.

提交回复
热议问题