【发布时间】:2017-01-08 18:43:16
【问题描述】:
我制作了一个模板和一个 auto 函数,用于比较 2 个值并返回最小的那个。 这是我的代码:
#include <iostream>
using namespace std;
// Template with a value returning function: PrintSmaller
template <typename T, typename U>
auto PrintSmaller(T NumOne, U NumTwo) {
if (NumOne > NumTwo) {
return NumTwo;
}
else {
return NumOne;
}
}
int main() {
int iA = 345;
float fB = 23.4243;
cout << PrintSmaller(iA, fB) << endl;
cout << PrintSmaller(fB, iA) << endl;
return 0;
}
但它不会编译,我在 VS 2015 上收到此错误: 错误 C3487 'int':所有返回表达式必须推导出为相同的类型:以前是 'float'
但是,如果我删除 if 语句并像这样编写函数 PrintSmaller问题:
auto PrintSmaller(T NumOne, U NumTwo) {
return (NumOne < NumTwo ? NumOne : NumTwo);
}
有什么区别?为什么第一个代码无法编译? 谢谢。
【问题讨论】:
-
三元语句可能会导致隐式转换。 This 可能是相关的。
-
你是用 -std=c++11 还是 -std=c++14 编译?
标签: c++