I have a class templated with typename T
. It contains a function,
template
myClass operator+(myClass
You are running into problems with template type deduction.
Both arguments are given "equal standing" when deducing the value of T
, and in this case the two arguments disagree -- one says T
should be int
, the other says T
should be double
.
The right way to fix this is with Koenig operators.
Make +=
and +
and the like friend
s of your class and implement inline:
template
class myClass {
// etc
public:
friend myClass operator+(myClass lhs, const T& rhs) {
lhs += rhs;
return std::move(lhs);
}
friend myClass& operator+=(myClass& lhs, const T& rhs) {
// do addition, depends on `a`
return *this;
}
};
this technique does something strange. It creates non-template
operators based on the template type of the class. These are then found via ADL (Koenig lookup) when you invoke +
or +=
.
You get one of these operators per template instantiation, but they aren't template operators, so const T&
isn't deduced, and conversion happens as expected.