I have a templated class for volume objects where operator+= is implemented as a member function and the operator+is implemented as non-member functions:
template <typename Class>
Class operator+(Class c1, const Class& c2) {
return c1 += c2;
}
// Add a constant to every element in the volume
template <typename Class, typename dataType>
Class operator+(Class c, dataType constant) {
return c += constant;
}
template <typename Class, typename dataType>
Class operator+(dataType constant, Class c) {
return c += constant;
}
Then I try to compile the following:
volume + 1.3;
where volume is a derived type from the templated volume class.
This gives me the following error:
error: ambiguous overload for ‘operator+’ in ‘volume + 1.3’
Why is the call ambiguous?
Your second template could be inferred with
Class = typeof(volume)anddataType = double, or your third template can be inferred withdataType = typeof(volume)andClass = double. The compiler can’t choose between them, even though quite possibly the third template would fail to instantiate.I’m assuming that
volumehas a user-defined type. If it has a built-in type, then I don’t think the call would be ambiguous, because for the purpose of operator overload resolution only, there are “real” functionsdouble operator+(double, double);etc, that would be selected before the templates are even considered.