函数重载不适用于C++中的模板?
Function overloading doesn't work with templates in C++?
我正在学习C++,我遇到了模板的使用。
所以我尝试使用模板实现以下两个函数,如下所示:
template <typename T>
T max(T a, T b){
return (a > b) ? a : b;
}
template <typename T>
T max(T a, T b, T c){
return max( max(a, b), c);
}
好吧,上面的实现在编译过程中抛出了一些错误。
这是错误的样子:
templateEx.cpp:13:14: error: call to 'max' is ambiguous
return max( max(a, b), c);
^~~
templateEx.cpp:17:22: note: in instantiation of function template specialization
'max<int>' requested here
cout<<"2, 3, 4 : "<<max(2,3,4);
^
/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/../include/c++/v1/algorithm:2654:1: note:
candidate function [with _Tp = int]
max(const _Tp& __a, const _Tp& __b)
^
templateEx.cpp:7:3: note: candidate function [with T = int]
T max(T a, T b){
^
1 error generated.
但另一方面,如果我不使用任何模板,并且我使用普通函数重载,如以下示例所示:
int max(int a, int b){
return (a > b) ? a : b;
}
int max(int a, int b, int c){
return max( max(a, b), c);
}
上面的代码编译没有错误。
有人可以解释一下吗?
我哪里出错了?
有一个std::max
是你与之冲突的。 您的代码中是否有using namespace std;
或using std::max
?
使用不同数量的参数重载模板函数应该有效。
相关文章:
- 继承函数的重载解析
- 你能重载对象变量名本身返回的内容吗
- 从父命名空间重载类型
- 使用C++中的模板和运算符重载执行矩阵运算
- 为什么这个运算符<重载函数对 STL 算法不可见?
- 重载操作程序时出错>>用于类中的字符串 memebr
- 一个关于在C++中重载布尔运算符的问题
- 不同翻译单元中不可重载的非内联函数定义
- 为什么使用SFINAE而不是函数重载
- 为什么我不能在 C++ 中的特定函数重载中调用同一函数的任何其他重载?
- 将重载的成员函数传递给函数模板
- c++:可变模板和函数重载
- 重载元组索引运算符-C++
- 如何使用重载的相等(==)运算符向测试用例添加描述
- 重载==不适用于二进制树
- 为什么Mat类的两个对象可以在不重载运算符+的情况下添加
- 重载运算符new[]的行为取决于析构函数
- 正在尝试重载二进制搜索树分配运算符
- 重载Singly Linked List中的赋值运算符
- 取消引用运算符不能重载