So I thought it would be a great idea to add template friends to my class for the standard operators (add, subtract, etc.), so I could do cool things like a = 1 / b;, but I seem to have run into a bit of a problem.
While gcc-4.4.0 accepts the following code just fine, both VS2005 and Comeau give an error about being ambiguous as to which operator to choose:
template <typename T>
class MyClass
{
public:
MyClass() : mVal(0) { }
MyClass(T val) : mVal(val) { }
template <typename U> MyClass<T> operator +(U val) const
{
MyClass<T> res = *this;
res.mVal += val;
return res;
}
template <typename U> friend MyClass<T> operator +(U val, const MyClass<T> &myc)
{
return myc + val;
}
private:
T mVal;
};
int main()
{
MyClass<int> a, b, c;
c = a + b;
}
Here's the actual error from Comeau (VS2005's error is pretty much the same):
"ComeauTest.c", line 27: error: more than one operator "+" matches these operands:
function template "MyClass<int> operator+(U, const MyClass<int> &)"
function template "MyClass<int> MyClass<T>::operator+(U) const
[with T=int]"
operand types are: MyClass<int> + MyClass<int>
c = a + b;
^
Any suggestions on what I might be doing wrong here, and how to possibly fix or work around this?