The following code works fine:
struct A {
int d;
A(int _d) : d(_d) {}
};
A operator+(const A& x, const A& y) {
return x.d + y.d;
}
int main() {
A x = 6;
cout << (x + 4).d << endl;
cout << (4 + x).d << endl;
}
However, if I make A
a template class, then it doesn't compile:
template<int p>
struct A {
int d;
A(int _d) : d(_d) {}
};
template<int p>
A<p> operator+(const A<p>& x, const A<p>& y) {
return x.d + y.d;
}
int main() {
A<0> x = 6; // OK
cout << (x + 4).d << endl; // error: no operator found or there is no acceptable convertion
cout << (4 + x).d << endl; // error: no operator found or there is no acceptable convertion
}
It works when I do explicit convertion A<0>(4)
or (A<0>)4
, but it's annoying.
I would like to know what causes this difference between "normal" and "template" classes, and how can I get implicit convertion working.
I'm using MSVC compiler, if that matters.