Reputation: 121
how can I convert integer to double? I have this code and the result of it is 15
, not 15.45
that's because the program takes the first number in as the type of the result, in this program that's integer
#include <iostream>
using namespace std;
template < class T1 , class T2 >
T1 smaller ( T1 a, T2 b ){
return (a<b?a:b);
}
int main(){
int x = 98;
double y = 15.45;
cout << smaller( x , y ) << endl;
return 0;
}
Upvotes: 0
Views: 275
Reputation: 137310
In C++11, you can use trailing return types together with decltype
and std::decay
(alternatively, std::common_type
):
template < class T1 , class T2 >
auto smaller ( T1 a, T2 b ) -> typename std::decay<decltype(a<b?a:b)>::type {
return (a<b?a:b);
}
The decay
is necessary to ensure that the function returns by value. Since you are taking the argument by value, you can't return a reference.
In C++14, you can use return type deduction:
template < class T1 , class T2 >
auto smaller ( T1 a, T2 b ) {
return (a<b?a:b);
}
Pre-C++11, you can write a mightily complicated promotion_traits
class with lots of specializations to determine the appropriate return type and return typename promotion_traits<T1, T2>::type
, or you can do what Antonio suggests and template smaller
on one template parameter instead, in which case it becomes std::min
but passing by value instead of const reference.
Upvotes: 2
Reputation: 20266
It's because your return type is templated on the type of the first input parameter, that in this case is integer.
You should have the same type for both input, and the output, and choose explicitly the type to be used in your function. For example:
template < class T >
T smaller ( T a, T b ){
return (a<b?a:b);
}
int main {
int x = 98;
double y = 15.45;
// cout << smaller( x , y ) << endl; //This wouldn't compile. It would compile if x and y had the same type.
// cout << smaller<int>( x , y ) << endl; //This would still return 15
cout << smaller<double>( x , y ) << endl;
}
As user2079303 mentions, the function that you are trying to implement is very similar to the std::min function available in the standard library.
Upvotes: 2
Reputation: 126
in your function call, try casting x as a double.
(double)x //or
static_cast<double>(x)
Upvotes: 0