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
I want to be able to also do this
std::cout << doubleTt1 + intTt2 << "\n";
What you'll probably need for this case are type traits. Basically, those are template classes containing typedef
s. You then partially specialize such a template to override the typedef
s.
(This is probably a bit naïve, but it should get the basic idea across.)
template
struct add_traits
{
typedef A first_summand_t; // <-- (kind of an "identity type")
typedef B second_summand_t; // <-- (ditto; both aren't strictly necessary)
typedef B sum_t; // <-- this is the interesting one!
};
Now you partially specialize that thing for various combinations of A
and B
:
template<>
struct add_traits
{
typedef int first_summand_t;
typedef int second_summand_t;
typedef int sum_t; // <-- overrides the general typedef
};
template<>
struct add_traits
{
typedef int first_summand_t;
typedef double second_summand_t;
typedef double sum_t; // <-- overrides the general typedef
};
template<>
struct add_traits
{
typedef double first_summand_t;
typedef int second_summand_t;
typedef double sum_t; // <-- overrides the general typedef
};
Now you could write a fairly generic add operation that went like this:
template
typename add_traits::sum_t add(A first_summand, B second_summand)
{
// ...
}
As you can see, you don't specify a concrete return type; instead, you let the compiler figure it out through the add_traits
template class. Once the compiler generates the code for a particular add
function, it will look up the types in the corresponding add_traits
class, and thanks to the partially specialized versions that you provided, you can make sure that certain type "combinations" will be applied.
P.S.: The same technique would e.g. also be useful when you want to subtract unsigned numbers. One unsigned int
subtracted from another can result in a negative answer; the result type would have to be a (signed
) int
.
P.P.S.: Corrections made according to the comments below.