Considering the following example, the line int a = objT + 5; gives ambiguous conversion which is handled in two ways, using the explicit cast which i think shouldn’t be necessary and replacing the use of conversion operators with member functions instead. and here, my question becomes should you still use conversions operators or not at all?
class Testable {
public:
Testable(int val = 0):x(val){}
operator int() const { return x; }
operator double() const { return x; }
int toInt() { return x; }
double toDouble() { return x; }
private:
int x;
};
int main()
{
Testable objT(10);
// ambiguous conversion
int a = objT + 5;
// why to use explicit cast when
// the conversion operator is for to handle
// this automatically
int b = static_cast<int>(objT) + 5;
// member functions
int c = objT.toInt() + 5;
}
Note that
int d = objT;is unambiguous, as isdouble e = objT;Here the compiler can unambiguously choose a conversion operator because of the exact match between the type of the left hand side and the return types from those conversion operators.The ambiguous conversion results from
objT + 5(also note:long f = objT;is also ambiguous). The problem is that you’ve taken away the essential information the compiler needs to mindlessly perform the disambiguation.The problem goes away if you get rid of either of those conversion operators. Since the underlying data member is an
int, I suggest getting rid ofoperator double().