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
If this is mainly for basic types, you could help yourself with a metafunction until the new standard rolls in. Something along the lines of
template::is_integer,
bool T2_is_int = std::numeric_limits::is_integer,
bool T1_is_wider_than_T2 = (sizeof(T1) > sizeof(T2)) > struct map_type;
template struct map_type { typedef T1 type; };
template struct map_type { typedef T2 type; };
template struct map_type { typedef T1 type; };
template struct map_type { typedef T2 type; };
template
typename map_type, TemplateTest >::type
operator+(TemplateTest const &t, TemplateTest const &u) {
return typename map_type, TemplateTest >::type(x + t1.x);
}
Of course, this is best combined with the char_traits idea:
template
struct add_traits
{
typedef A first_summand_t;
typedef B second_summand_t;
typedef typename map_type::type sum_t;
};
So that you can still specialise for types that don't have a numeric_limits overload.
Oh, and in production code, you'll probably want to properly namespace that and add something for signed/unsigned mismatches in integer types.