C++ 函数模板错误

标签 c++ templates

我刚刚开始使用 C++ 中的函数模板。我正在使用 these教程。我正在尝试实现一个类似这样的基本代码。

#include<iostream>
using namespace std;

template<class t>
t max(t a,t b){
    t max_value;
    max_value = (a>b)?a:b;
    return max_value;
}

int main(){
    int a=9,b=8,c;
    c=max<int>(a,b);
    cout<<c;
    return 0;
}

但是我得到以下错误。

/usr/bin/gmake" -f nbproject/Makefile-Debug.mk QMAKE= SUBPROJECTS= .build-conf
gmake[1]: Entering directory `/home/gursheel/NetBeansProjects/project_q7'
"/usr/bin/gmake"  -f nbproject/Makefile-Debug.mk dist/Debug/GNU-Linux-x86/project_q7
gmake[2]: Entering directory `/home/gursheel/NetBeansProjects/project_q7'
mkdir -p build/Debug/GNU-Linux-x86
rm -f build/Debug/GNU-Linux-x86/main.o.d
g++    -c -g -MMD -MP -MF build/Debug/GNU-Linux-x86/main.o.d -o build/Debug/GNU-Linux-x86/main.o main.cpp
main.cpp: In function ‘int main()’:
main.cpp:16:19: error: call of overloaded ‘max(int&, int&)’ is ambiguous
main.cpp:16:19: note: candidates are:
main.cpp:4:3: note: t max(t, t) [with t = int]
In file included from /usr/include/c++/4.7/bits/char_traits.h:41:0,
                 from /usr/include/c++/4.7/ios:41,
                 from /usr/include/c++/4.7/ostream:40,
                 from /usr/include/c++/4.7/iostream:40,
                 from main.cpp:1:
/usr/include/c++/4.7/bits/stl_algobase.h:210:5: note: const _Tp& std::max(const _Tp&, const _Tp&) [with _Tp = int]
gmake[2]: *** [build/Debug/GNU-Linux-x86/main.o] Error 1
gmake[2]: Leaving directory `/home/gursheel/NetBeansProjects/project_q7'
gmake[1]: *** [.build-conf] Error 2
gmake[1]: Leaving directory `/home/gursheel/NetBeansProjects/project_q7'
gmake: *** [.build-impl] Error 2


BUILD FAILED (exit value 2, total time: 318ms)

我无法理解错误到底是什么。任何帮助将不胜感激。

最佳答案

您需要删除:

using namespace std;

你正在与 std::max 发生冲突.这是原因之一Why “using namespace std;” is considered bad practice这是C++ FAQs take on it .输入 std::cout 确实没那么糟糕,您很快就会习惯添加 std::,从长远来看,它只会为您省去麻烦。

关于C++ 函数模板错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18216360/

相关文章:

c++ - 加载共享库时出错

c++ - Visual Studio MFC 工具栏编辑器图标顺序不会更新

c++ - 在 Linux 下以编程方式更改屏幕分辨率而无需监视器?

c++ - 是否可以在编译时检测以下赋值?

Spring Boot 使用带有 JSP 模板的资源模板文件夹而不是 webapp 文件夹?

c++ - 获取 ostream 的插入运算符

c++ - 基于构建配置的链接库[cmake]

c++ - 接受对类模板参数的左值和右值引用

c++ - 在 C++ 中使用模板初始化的静态结构指针

c++ - 如何使用 C++ native 代码链接到 Android Studio 项目中的 GLES2