In the following, I’m expecting obj to be converted to an int but why does it returns operator + ambiguous in the following?
class MyClass
{
public:
MyClass(int X = 0, double Y = 0):x(X), y(Y){}
operator int() const { return x; }
operator double() const { return y; }
private:
int x;
double y;
};
int main()
{
MyClass obj(10, 20);
int x = obj + 5; //obj converted to int
}
Because both conversions are equivalent, it’s ambiguous. Remember that the C++ language directly defines
+for arguments ofdoubleandint, there is no standard conversion involved.So neither of these functions is better than the other:
double operator+ (double, int)— requires one user-defined conversion and no standard conversionsint operator+ (int, int)— requires one user-defined conversion and no standard conversionsYou’ll need to provide all the usual arithmetic operators yourself, if you want to make this work, and not rely on implicit conversion operators.
double operator+ (const MyClass&, int)— requires one standard conversionint operator+ (const MyClass&, double)— requires no conversionsNow
obj + 5will have an unambiguous best match.C++0x draft n3245 says, in section
[over.built]