Based on the answer in Implicit conversion when overloading operators for template classes I was able to write the following code that works perfectly fine (simplified example):
namespace my_library {
template <typename T>
struct Number {
T n;
inline Number(T n) : n(n) { }
friend Number<T> operator+(const Number<T> &a, const Number<T> &b) {
return Number<T>(a.n + b.n);
}
};
}
int main() {
return (int) (4 + my_library::Number<double>(3)).n; // returns 7
}
All I want to do is make it so that operator+
is not inlined within the definition of Number
(but stays in the header file) while everything still works the same way - see the expression in the main
function. Note that it requires that the integer 4 gets implicitly converted to double
and then to Number<double>
. I followed a comment linking to Binary operator overloading on a templated class but that solution did not work - the overloaded operator is no longer matched. Is there any way to make this work and have the body of the operator outside the struct
definition? (Without complicating the operator interface or adding more overloads - in those cases I'd rather just keep it inlined.)