+ 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)
9 odpowiedzi
+ 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 .
+ 9
c++
+ 6
see this code. it may help you
https://code.sololearn.com/cgXS9y00KD6C/?ref=app
+ 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...
+ 1
x>y (5.5 > 4) = true
which then returns the value of x
(x is 5.5)
(false would return y)
+ 1
I know but why is it 5 not 5.5 it doesn't specify float or int
+ 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
+ 1
у вас возвращаемый тип int он усекает дробную часть, поставьте возвращаемый тип U вместо T
0
What’s this programming language?