【发布时间】:2016-05-02 07:09:36
【问题描述】:
我有一个模板函数,它接受两种数据类型 - 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 和 double 的输入类型并确定 double 是最佳输出类型? C++ 是静态类型的,因此返回类型不能依赖于输入值。
-
如果你试图根据输入来决定函数的返回类型,这在 C++ 中是不可能的。
标签: c++ templates c++11 casting