我所要做的就是实现平等的算法。然而,当我用几个字符串进行测试时,我会得到一个模糊错误。我认为编译器不能区分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)发布于 2013-11-04 18:29:14
问题是,参数(来自std::string的迭代器)位于名称空间std中,而在这个名称空间中,由于参数依赖查找(ADL),有另一个名为equal的算法是候选的。您需要显式限定您的算法:
std::cout << "a and b are " << ::equal(a.begin(), a.end(), b.begin()) << std::endl;
// ^^ here请注意,C++标准不要求迭代器是std中的类型,而是允许它,您的编译器/标准库决定使用此选项。
发布于 2013-11-04 18:33:17
这是所谓的依赖于参数的名称查找的结果。在C++中有标准算法std::equal。编译器看到函数调用的参数属于命名空间std。因此,它还考虑到名称空间std中名称相等的任何函数。因此,它找到了两个函数:一个是由您定义的,另一个是在命名空间std中声明的。若要转义错误,请使用函数的完全限定名,即::equal。顺便说一句,您不正确地使用您的函数,这样的用法有未定义的行为。第二个范围必须至少具有与第一个范围相同的大小。在您的示例中,您使用字符串a和c,c的大小小于a的大小。
https://stackoverflow.com/questions/19774474
复制相似问题