我有一个模板函数,它需要两种数据类型-int和double,并返回较小的数据类型,现在,如何推断该函数将返回的类型?现在,我正在丢失小数点后的部分。
#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;
}
三元运算符的标准行为是执行“常规算术转换”。在这种情况下,将提升int
为a的方法double
。之所以与之相同,auto x=1/1.0;
是double
因为提升了整数分子使其与double
分母兼容。
请参见C ++ 11中“ auto var = {condition}?1:1.0”的类型是什么的答案?是double还是int?。有“外行条款”和标准报价答案。两者都应该有所帮助。
但是,您要做的是将类型强制为“ First”:
template <class First, class Second>
First smaller(First a, Second b){
return (a < b ? a : b);
}
查看您输入的返回类型smaller
。因此发生的事情是将其提升为a double
,然后转换为int
返回值。
看看这个:
#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;
}
预期产量:
15
15.5
15.5
15.5
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句