我要做的就是实现相等算法。但是,当我使用几个字符串进行测试时,出现歧义错误。我认为编译器无法区分 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;
}
主要内容
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;
错误信息
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/