I have a template function that takes two data types - int and double and returns the one which is smaller, Now, How can I infer the type that will be returned by this function? Right now, I am losing the parts after the decimal points.
#include <iostream>
using namespace std;
template <class First, class Second>
First smaller(First a, Second b){
return (a < b ? a : b);
}
int main () {
int x = 100;
double y = 15.5;
cout<< smaller (x,y) << endl;
}
The standard behaviour of the ternary operator is to perform 'usual arithmetic conversions'. The means promoting the int
to a double
in this case. That's the same as in auto x=1/1.0;
is a double
because of promotion of the integer numerator to be compatible with the double
denominator.
See the answers to What is the type of "auto var = {condition} ? 1 : 1.0" in C++11? Is it double or int?. There are 'laymans terms' and standards quote answers. Both should help.
However what you've done is force the type to be `First':
template <class First, class Second>
First smaller(First a, Second b){
return (a < b ? a : b);
}
Look at the return type you put in for smaller
. So what is happening is it's being promoted to a double
and then converted to an int
return value.
Take a look at this:
#include <iostream>
template <class First, class Second>
First smaller(First a, Second b){
return (a < b ? a : b);
}
template <class First, class Second>
auto smaller_auto(First a, Second b){
return (a < b ? a : b);
}
int main() {
int x=100;
double y=15.5;
std::cout<< smaller(x,y)<<std::endl; //First is int returns an int.
std::cout<< smaller(y,x)<<std::endl;//First is double returns double.
std::cout<< smaller_auto(x,y)<<std::endl; //Performs the usual arithemtic conversions (returns double).
std::cout<< smaller_auto(y,x)<<std::endl;//Performs the usual arithemtic conversions (returns double).
return 0;
}
Expected output:
15
15.5
15.5
15.5
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments