c++ - C++ 模板函数的重载错误
问题描述
我正在尝试使用函数模板进行一些练习,如下例所示:
#include <iostream>
using namespace std;
template <class T>
T max(T a, T b)
{
return a > b ? a : b;
}
int main()
{
cout << "max(10, 15) = " << max(10, 15) << endl;
retun 0;
}
但我得到了以下错误。有人能认出问题出在哪里吗?
..\src\main.cpp:59:40: error: call of overloaded 'max(int, int)' is
ambiguous
cout << "max(10, 15) = " << max(10, 15) << endl;
^
..\src\main.cpp:16:3: note: candidate: 'T max(T, T) [with T = int]'
T max(T a, T b)
^~~
In file included from c:\mingw\include\c++\8.1.0\bits\char_traits.h:39,
from c:\mingw\include\c++\8.1.0\ios:40,
from c:\mingw\include\c++\8.1.0\ostream:38,
from c:\mingw\include\c++\8.1.0\iostream:39,
from ..\src\main.cpp:9:
c:\mingw\include\c++\8.1.0\bits\stl_algobase.h:219:5: note:
candidate: 'constexpr const _Tp& std::max(const _Tp&, const _Tp&)
[with _Tp = int]'
max(const _Tp& __a, const _Tp& __b)
对不起,我是模板新手。谢谢你的帮助。
解决方案
您对模板的使用是正确的,但编译器抱怨已经有一个max
使用相同参数调用的函数。
它的全名是std::max
,但是因为你写using namespace std
了它max
,编译器不知道要调用哪个函数。
解决方案是不使用using
,请参阅为什么“使用命名空间标准”被认为是不好的做法?.
推荐阅读
- javascript - 通过 nunjucks-webpack-loader 在 nunjucks 中翻译
- javascript - RxJS Observable.combineLatest 永远不会完成
- ios - Swift 5 Closures explained
- javascript - 如何使用 Selenium 和 Java 提取 DOM 中的文本
- java - Apache Commons Lang 类“ArrayUtils”中“添加”的时间复杂度
- php - MongoDB GridFS 按 ID 查找文件
- java - 有没有人在 Web 应用程序中使用 MSAL4J java 库为 ADFS 身份验证服务器实现身份验证?
- python - 如何在 Python 中处理多个项目的一个公共 lib 文件夹
- ios - 使用 unarchivedObjectOfClass 复制 UIButton - 对象不能为 nil
- javascript - React native 拖放动画。查看 onLongPress