2013-11-04 106 views
1

我想要做的就是實現相等的算法。但是,當我用幾個字符串測試時,我得到一個模糊性錯誤。我認爲編譯器不能區分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) 

回答

2

的問題是,參數(從std::string的迭代器)是在命名空間std和這個命名空間中,有一個名爲另一種算法equal由於參數相關查找(ADL),這是一個候選人。你需要明確限定你的算法:

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

注意的是,C++標準不要求迭代器是一個類型std,但允許它和你的編譯器/標準庫決定使用此選項。

+0

是的,當我在錯誤信息中看到'算法'這個詞時,我想這可能是這種情況,但不知道如何解決它。謝謝。 – Ares

1

這是所謂的基於參數的名稱查找的結果。在C++中有標準算法std :: equal。編譯器會發現函數調用的參數屬於名稱空間std。所以它也考慮名字空間標準中名稱相等的任何函數。結果它找到了兩個函數:一個由你定義,另一個在名字空間std中聲明。 爲了避免錯誤,請使用您的函數的完全限定名稱::。 順便說一句,您錯誤地使用您的功能,這種用法有未定義的行爲。第二個範圍必須至少與第一個範圍相同。在你的例子中,你使用字符串a和c,c的大小小於a的大小。