Reputation: 407
I have this code:
template <class T>
T GetMax (T a, T b) {
return (a>b?a:b);
}
int main () {
int i=51, j=26, k;
long l=100, m=15, n;
k=GetMax(i,j);
n=GetMax(l,m);
cout << k << endl;
cout << n << endl;
return 0;
}
How can I change the data type of variables k and n so that they can be dynamic enough to accept the returned value. If the returned value is a double, the k and n will automatically be double, so I need not bother whether I am passing in int or double.
I tried searching it in online and in my books but no luck. Can you Plz help me? I am new to templates.
Upvotes: 3
Views: 136
Reputation: 867
You could use reference to make compiler warn you if you don't behave.
template <class T>
void GetMax (T a, T b, T& output) {
output = (a>b?a:b);
}
But if you can use C++11, use auto
instead.
Upvotes: 1
Reputation: 1542
You can't but you don't need to.
GetMax will always be called in the context where you know what types you passed in, so you know what the return type could be.
For example, if you pass in two ints, the result will be int. If you pass in a double and a long, it will be a double.
Think of templates as type safe macros. Replace the call of the function by the body of the function with the types replaced and that's what it will do.
Upvotes: 2
Reputation: 110768
In C++11, you can use auto
:
auto k = GetMax(i,j);
auto n = GetMax(l,m);
The types of k
and n
are deduced from the expression used to initialise them.
Prior to C++11, you would need to give the types explicitly. However, you should always be able to write the types in some form or another, since you know the types of the arguments.
Upvotes: 9