I have a template class with an overloaded + operator. This is working fine when I am adding two ints or two doubles. How do I get it to add and int and a double and return th
The add operator should generally be a free function to avoid preferring any operand type as @Stephen nicely explains. This way it's completely symmetric. Assuming you have a function get
that returns the stored value, this can be like the following (alternatively, you can declare it as a friend if such a get
function does not exist)
template
TemplateTest??> operator+(const TemplateTest& t1, const TemplateTest& t2)
{
return TemplateTest??>(t1.get() + t2.get());
}
The problem now is to find a result type. As other answers show this is possible with decltype
in C++0x. You can also simulate this by using the rules of the ?:
operator which are mostly quite intuitive. promote<> is a template that uses that technique
template
TemplateTest< typename promote::type >
operator+(const TemplateTest& t1, const TemplateTest& t2)
{
return TemplateTest< typename promote::type >(t1.get() + t2.get());
}
Now for example if you add double
and int
, it will yield double
as the result. Alternatively as shown in the promote<>
answer, you can also specialize promote
so you can apply it directly to TemplateTest
types.