C++模板问题

Vij*_*jay 0 c++ templates stl

我是c ++模板的新手.我正在尝试一些小程序.

    CPP [80]> cat 000001.cpp 000001.hpp
#include <iostream>
#include <string>
#include "000001.hpp"

int main()
{
    int i = 42;
    std::cout << "max(7,i):   " << ::max(7,i) << std::endl;

    double f1 = 3.4;
    double f2 = -6.7;
    std::cout << "max(f1,f2): " << ::max(f1,f2) << std::endl;

    std::string s1 = "mathematics";
    std::string s2 = "math";
    std::cout << "max(s1,s2): " << ::max(s1,s2) << std::endl;
}

template <typename T>
inline T const& max (T const& a, T const& b)
{
        return  a < b ? b : a;
}
Run Code Online (Sandbox Code Playgroud)

当我编译这个程序时:

我收到以下错误:

    CPP [78]> /opt/aCC/bin/aCC -AA 000001.cpp
Error (future) 229: "/opt/aCC/include_std/string.cc", line 164 # "Ambiguous overloaded function call; a
    function match was not found that was strictly best for ALL arguments. Two functions that matched
    best for some arguments (but not all) were "const unsigned long &max<unsigned long>(const unsigned
    long &,const unsigned long &)" ["000001.hpp", line 2] and "const unsigned long &std::max<unsigned
    long>(const unsigned long &,const unsigned long &)" ["/opt/aCC/include_std/algorithm", line 1762]."
    Choosing "const unsigned long &max<unsigned long>(const unsigned long &,const unsigned long &)"
    ["000001.hpp", line 2] for resolving ambiguity.
            _C_data = _C_getRep (max (_RW::__rw_new_capacity (0, this),
                                 ^^^
Warning:        1 future errors were detected and ignored. Add a '+p' option to detect and fix them before they become fatal errors in a future release. Behavior of this ill-formed program is not guaranteed to match that of a well-formed program
Run Code Online (Sandbox Code Playgroud)

请问有谁请告诉我究竟是什么错误?

ava*_*kar 7

你可能包括<iostream.h>而不是<iostream>某个地方.前者现在已经存在一段时间了,但出于兼容性原因,编译器仍然接受include并将其替换为

#include <iostream>
using namespace std;
Run Code Online (Sandbox Code Playgroud)

这导致std::max被带到全局命名空间,从而导致模糊.更换<iostream.h><iostream>或重命名max功能,问题应该会消失.

编辑:你显然修复了包含,但我打赌你还有一些using namespace std;地方.你需要摆脱它.事实上,你永远不应该using namespace在全球范围内使用.

编辑:你可能也有using std::max某个地方.你也需要摆脱它.