函数模板过载问题

function template overload issue

本文关键字:问题 函数模板      更新时间:2023-10-16

为什么我收到一个错误说:

  1. 错误 C2668:"max":对重载函数的不明确调用
  2. 错误 C2780:"常量 T 和最大值(常量 T &,常量 T 和,常量 T &)":需要 3 个参数 - 提供 2 个参数。

在以下代码中:

template<typename T>
inline T const& max(T const& i, T const& j)
{
  cout<<"Using template with 2 args."<<endl;
  return (i>j) ? i : j;
}
template<typename T>
inline T const& max(T const& i, T const& j, T const& k)
{
  cout<<"Using template with 3 args."<<endl;
  return max(max(i,j),k);
}
void main()
{
  cout<< ::max(1,2,3)<<endl;    
}

在调用它之前,我已经定义了 2 参数模板函数。

删除using namespace std,因为有std::max参与搜索,这就是您收到第一个错误的原因。第二个错误只是说,有明确的变体,但它们应该收到 3 个参数。