我要做的就是实现平等算法。但是,当我用几个字符串进行测试时,会出现歧义错误。我认为编译器无法区分A和B。这是为什么?

template <class A, class B> bool equal(A beg, A end, B out)
{
    while(beg != end) {
        if(*beg == *out) {
            ++beg;
            ++out;
        }
        else return false;
    }
    return true;
}
MAIN
std::string a("This is a string");
std::string b("This is a string");
std::string c("String c");
std::cout << "a and b are " << equal(a.begin(), a.end(), b.begin()) << std::endl;
std::cout << "a and c are " << equal(a.begin(), a.end(), c.begin()) << std::endl;
ERROR MESSAGE
procedures_main.cpp:17:35: error: call to 'equal' is ambiguous
    std::cout << "a and b is " << equal(a.begin(), a.end(), b.begin()) << std::endl;
                                  ^~~~~
/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/../lib/c++/v1/algorithm:1105:1: note:
      candidate function [with _InputIterator1 = std::__1::__wrap_iter<char *>, _InputIterator2 =
      std::__1::__wrap_iter<char *>]
equal(_InputIterator1 __first1, _InputIterator1 __last1, _InputIterator2 __first2)
^
./procedures.hpp:73:34: note: candidate function [with A = std::__1::__wrap_iter<char *>, B = std::__1::__wrap_iter<char
      *>]
template <class A, class B> bool equal(A beg, A end, B out)

最佳答案

问题在于参数(来自std::string的迭代器)位于命名空间std中,并且在此命名空间中,存在另一种称为equal的算法,由于依赖于参数的查找(ADL)而成为候选算法。您需要明确限定算法:

std::cout << "a and b are " << ::equal(a.begin(), a.end(), b.begin()) << std::endl;
//                             ^^ here

请注意,C++标准不需要迭代器为std中的类型,但是允许它,并且您的编译器/标准库决定使用此选项。

关于c++ - 实现平等算法,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/19774474/

10-08 22:03
查看更多