首页 > 解决方案 > 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)

对不起,我是模板新手。谢谢你的帮助。

标签: c++eclipsetemplates

解决方案


您对模板的使用是正确的,但编译器抱怨已经有一个max使用相同参数调用的函数。

它的全名是std::max,但是因为你写using namespace std了它max,编译器不知道要调用哪个函数。

解决方案是不使用using,请参阅为什么“使用命名空间标准”被认为是不好的做法?.


推荐阅读