函数模板调用未解决

时间:2019-12-30 19:50:20

标签: c++ templates

在以下代码段中,对max(2,3)的第二个示例调用未调用该函数。而且没有编译时间/运行时错误。 有人可以解释这是怎么回事吗?

template<class T1>
void max(int a,int b)
{
        cout<<"max() called\n";
}

max<int>(2,3); //this calls max(2,3)
max(2,3); //surprisingly no error and max() isn't called here

1 个答案:

答案 0 :(得分:1)

您没有使用模板。使用它看起来像这样:

template<class T1>
void max(T1 a,T1 b)

其他所有内容都相同。另外,还有一个函数在std名称空间中对其进行了阴影处理,将函数名称更改为max1将纠正此问题或删除名称空间。我希望这会有所帮助。

它看起来像这样:

#include<iostream>
// because the std namespace is not included there will be no shadowing
template<class T1>
void max(T1 a, T1 b)
{
        std::cout<<"max() called\n";
}