c++ - 编写一个函数,通过判断每个参数的类型自动确定返回值
问题描述
标头中的max()
函数<algorithm>
不支持不同数据类型的两个参数。因此,我尝试使用template
and#if
和宏编写自己的代码。到目前为止我的代码:#else
#endif
#include <iostream>
template <class type1, class type2>
#if sizeof(type1) >= sizeof(type2)
type1 max(type1 a, type2 b){
return (a > b) ? a : b;
}
#else
type2 max(type1, type2){
return (a > b) ? a : b;
}
#endif
int main(){
int a, d; long long b, c;
std::cin >> a >> b;
std::cout << "The max is " << max(a, b) << ".\n";
std::cin >> c >> d;
std::cout << "The max is " << max(c, d) << ".\n";
return 0;
}
现在显然代码无效,因为它引发了语法错误(也许我误解了这些宏的工作方式,因为我对这个主题以及模板都是新手):
|Line 05 | error: missing binary operator before token "type1" |
| | In function 'type2 max(type1, type2)': |
|Line 11 | error: 'a' was not declared in this scope |
|Line 11 | error: 'b' was not declared in this scope |
我想知道是否可以构建这样的程序以及如何构建。
解决方案
您不能将宏与这样的模板混合使用;宏将首先被评估,并且不会像您预期的那样与模板交互。
您可以使用std::conditional
显式声明返回类型,
// if sizeof(type1) >= sizeof(type2), then declare the return type as type1
// otherwise type2
template <class type1, class type2>
std::conditional_t<sizeof(type1) >= sizeof(type2), type1, type2>
max(type1 a, type2 b) {
return (a > b) ? a : b;
}
或者你可以只使用auto
. 返回类型将自动推断为由条件运算符确定的通用类型。对于max(int, long long)
and max(long long, int)
,返回类型将是long long
,与上述版本相同。(请注意,通用类型可能与上述版本不同;例如,max(short, bool)
返回类型将int
代替short
.)
template <class type1, class type2>
auto max(type1 a, type2 b) {
return (a > b) ? a : b;
}
推荐阅读
- css - 渐变下划线文本
- react-native - “navigationOptions”中的弃用:-“header:null”将被删除
- pdftotext - 如何在 pdftotext.exe 中使用边距 arg
- php - 在 INSERT 语句中使用 RIGHT JOIN
- javascript - 简单的十进制百分比加载器
- c++ - 多态成员变量 - 类设计
- reactjs - 使用 React,我如何在播放和暂停视频时保持状态?
- css - 更改输入自动填充样式
- python - 如何在 PyCharm 中使用 Anaconda 包而无需重新安装它们?
- python - 我可以在画布行(tkinter)中设置标签位置吗?