【问题标题】:call to an overloaded function while calling template调用模板时调用重载函数
【发布时间】:2013-09-21 11:27:20
【问题描述】:

我正在调用一个模板来从两个值中找出一个最小值 代码是:

#include<iostream>
#include <cstdlib>

using namespace std;

template<class T>
T min(T a,T b)
{
    return (a<b)?a:b;
}


int main(int argc, char** argv) {
int d,y;
std::cout<<"enter two integer values";
std::cin>>d>>y;
cout<<"you entered"<<d<<y;
std::cout<<"the minimum of the two is "<<min(d,y);
float p,q;
std::cout<<"enter float values";
std::cin>>p>>q;
cout<<"you entered"<<p<<q;
std::cout<<"the minimum of the float values is "<<min(p,q);
char w,a;
std::cout<<"enter the two characters";
std::cin>>w>>a;
cout<<"you entered"<<w<<a;
std::cout<<"the minimum of the two characters is "<<min(w,a);
return 0;

}

它说对重载函数的调用不明确

【问题讨论】:

  • 你知道有std::min吗?
  • 更具体地说,template&lt; class T &gt; const T&amp; std::min( const T&amp; a, const T&amp; b )

标签: c++ templates ambiguous


【解决方案1】:

删除

using namespace std;

因为 std 中还有一个 min() 函数。

【讨论】:

    【解决方案2】:

    您收到错误是因为在命名空间 std 中定义了一个名为 std::min 的标准函数,您的程序允许编译器在没有显式引用的情况下使用它。

    删除

    using namespace std;
    

    并将std:: 限定符添加到cout 缺少的地方以解决此问题。

    Demo of your program compiling on ideone.

    【讨论】:

      【解决方案3】:

      使用::min(d,y) 表示您引用全局命名空间中的函数。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多