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
Stephen has already given a good explanation of the problems you may encounter with this. You can define overloads for all the possible combinations of all the instantiations of the template (so, you'd effectively have operators defined for double + double, int + double, double + int, etc.). This can get unwieldy fast and can be difficult to keep track of which combinations are supported.
You might be better off using a non-member function named something like Add()
. The advantage of doing this is that you can specify the return type. The disadvantage is that you have to specify the return type. :-) In general, though, this is better than performing unexpected conversions automatically.
template <typename R, typename T, typename U>
TemplateTest<R> Add(const TemplateTest<T>& t, const TemplateTest<U>& u)
{
return TemplateTest<R>(t.x + u.x);
}
invoked as:
std::cout << Add<double>(intTt1, doubleTt1) << std::endl;
C++0x will add support for a number of language features that will make this much simpler and will allow you to write a reasonable operator+
overload:
template <typename T, typename U>
auto operator+(const TemplateTest<T>& t, const TemplateTest<U>& u)
-> TemplateTest<decltype(t.x + u.x)>
{
return TemplateTest<decltype(t.x + u.x)>(t.x + u.x);
}
This will ensure that the usual arithmetic conversions (integer promotion, conversion to floating point, etc.) are performed and you end up with the expected result type.
Your C++ implementation may support these C++0x features already; you'd want to consult the documentation of whatever compiler you are using.
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<typename T1, typename T2>
TemplateTest<???> operator+(const TemplateTest<T1>& t1, const TemplateTest<T2>& 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<typename T1, typename T2>
TemplateTest< typename promote<T1, T2>::type >
operator+(const TemplateTest<T1>& t1, const TemplateTest<T2>& t2)
{
return TemplateTest< typename promote<T1, T2>::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.
Get a compiler that supports the new C++0x decltype operator.
template < typename T1, typename T2 >
auto add(T1 t1, T2 t2) -> decltype(t1+t2)
{
return t1 + t2;
}
Now you don't have to fart around with those "traits" classes.
This is technically possible by defining an implicit case to TemplateTest<double>
:
operator TemplateTest<double>() {
return TemplateTest<double>((double)x);
}
Practically this probably isn't a great idea though, as x
can't necessarily be safely cast to a double; it happens that you're using a TemplateTest<int>
here, but you could be using a TemplateTest<std::string>
later. You should probably rethink what you're doing and decide if you're sure you actually need this behavior
You can add int and double values by using templates.In the function, specify 2 arguments and while passing values to the functions specify its types in angular brackets.
example:
//template
template<typename T1, typename T2>
void add(T1 a, T2 b)
{
//for adding values
cout<<"\n\nSum : "<<a+b;
}
int main ()
{
//specify types while passing values to funcion
add<int,double>(4,5.5454);
add<float,int>(4.7,5);
add<string,string>("hi","bye");
return 0;
}
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 <typename A, typename B>
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<int, int>
{
typedef int first_summand_t;
typedef int second_summand_t;
typedef int sum_t; // <-- overrides the general typedef
};
template<>
struct add_traits<int, double>
{
typedef int first_summand_t;
typedef double second_summand_t;
typedef double sum_t; // <-- overrides the general typedef
};
template<>
struct add_traits<double, int>
{
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 A, typename B>
typename add_traits<A,B>::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.