keyvan vafaee keyvan vafaee -4 years ago 74
C++ Question

using template ( same result)

Why is the output of these two programs the same?

Example 1

template < typename T1, typename T2 >
T1 sumit(T1 a, T2 b)
{
T2 result = (a + b);
return result;
}
int main()
{
cout << sumit(1, 'a');
}


Example 2

template < typename T1, typename T2 >
T1 sumit(T1 a, T2 b)
{
T1 result = (a + b);
return result;
}

int main()
{
cout << sumit(1, 'a');
}


What is deference between T1 result and T2 result?

Answer Source

In either case you are passing first argument as an int and second as char. So, T1 becomes int and T2 becomes char.

In first case you are storing the result of a+b in a char variable (as T2 here is a char), but while returning the result it becomes an int. In your code you are just adding 1 and 'a' and ASCII value of 'a' is 97. So the returned result is 98. Both char and int returns same answer here because a char can also store 98 (char is 1 byte and its range is -128 to 127; int is 4 bytes).

In your second program you are storing the sum in an int variable (as T1 is int), which can definitely store the sum of 1+'a' which is 98 (int value).

So you are getting same result in both the cases.

If you had added some large int value instead of 1 the returned result by both the programs would differ. For example, if you pass 1200 and 'a' to sumit() function, then the first program will return 17 due to overflow of char range but second program will return 1297 (no overflow in case of int).

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download