Consider the following classes, where the first is templated. Both are meant to hold a numeric value.
template<typename T>
struct foo
{
foo(T val) : val{ val } {}
T val;
};
struct bar
{
bar(double val) : val{ val } {}
double val;
};
I want to define a way to add these classes together to get a new one with a different value.
template<typename T>
foo<T> operator+(foo<T> a, foo<T> b)
{
return foo<T>(a.val + b.val);
}
bar operator+(bar a, bar b)
{
return bar(a.val + b.val);
}
When I use these operators with implicit conversion, the operator using object of type foo
doesn't use the implicit conversion on the double value to apply my overloaded operator, even though it can do it for the non-template class. The result is that there is no operator matching the types in that expression.
int main()
{
foo<double> foo_value(11.0);
bar bar_value(11.0);
foo<double> ev1 = foo_value + 1.0; // no operator matches these operands
bar ev2 = bar_value + 1.0;
}
Does the operator have to be explicitly instantiated first? If so, a) how does that look like, and b) why isn't the instantiation done implicitly, if it can be done when initializing an object of type foo<double>
?
If the standard doesn't support any sort of resolution without explicitly casting 1.0
to a value of type foo<double>
, I presume the only other possibility is defining operator overloads for each type I want to use like that (for both lhs and rhs)?