+ 3

Why does thus code output 5

template <class U, class T> T func(U x, T y) return (x>y)?x:y int main cout << func(5.5, 4)

15th Aug 2017, 3:17 AM
HJ🐓TDM
9 Réponses
+ 2
return type-> T func(U x, T y) now when u call the function as func(5.5 , 4) ^ ^ double int func(U , T) U - becomes double T - becomes int since return type is T therefore the output is int of 5.5 which is 5. Hope this helps .
19th Aug 2017, 1:09 PM
Rishabh Agrawal
Rishabh Agrawal - avatar
+ 9
c++
19th Aug 2017, 2:26 AM
jay
jay - avatar
+ 6
15th Aug 2017, 4:15 AM
jay
jay - avatar
+ 3
Because when template function used you have: the first argument is type double, the second is type int... So in template function the U type is equal "double", the T type is equal "int". As returning type is T, so in this case the function return "int"... Thus "5.5" must be casted to "int" and you have a whole part of it...
15th Aug 2017, 3:36 AM
Yuri Zavyalov
+ 1
x>y (5.5 > 4) = true which then returns the value of x (x is 5.5) (false would return y)
15th Aug 2017, 3:26 AM
Jordan Chapman
Jordan Chapman - avatar
+ 1
I know but why is it 5 not 5.5 it doesn't specify float or int
15th Aug 2017, 3:27 AM
HJ🐓TDM
+ 1
a template is a way to create a function that is universal to any data type. So it doesn't need to specify since it knows it's dealing with a float
15th Aug 2017, 3:28 AM
Jordan Chapman
Jordan Chapman - avatar
+ 1
у вас возвращаемый тип int он усекает дробную часть, поставьте возвращаемый тип U вместо T
24th Aug 2017, 6:27 PM
eSkry
eSkry - avatar
0
What’s this programming language?
19th Aug 2017, 1:58 AM
TECNO MUNDO
TECNO MUNDO - avatar