如何根据条件推断可以返回类型的函数的类型?

Son*_*nny 3 c++ templates casting c++11

我有一个模板函数,它接受两种数据类型 - 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;

}
Run Code Online (Sandbox Code Playgroud)

Per*_*xty 5

三元运算符的标准行为是执行"通常的算术转换".在这种情况下促进inta 的手段double.这auto x=1/1.0;double因为促进整数分子与double分母兼容.

请参阅C++ 11中"auto var = {condition}?1:1.0"的类型是什么?是双重还是整数?.有'laymans条款'和标准引用答案.两者都有帮助.

但是你所做的就是强制类型为"First":

template <class First, class Second>
First smaller(First a, Second b){
   return (a < b ? a : b);
}
Run Code Online (Sandbox Code Playgroud)

查看您输入的返回类型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;
}
Run Code Online (Sandbox Code Playgroud)

预期产量:

15
15.5
15.5
15.5
Run Code Online (Sandbox Code Playgroud)