2013-04-21 83 views
0

在下面的代碼中,我試圖搜索一個字符串數組,我傳遞給特定字符串的模板函數,但是我得到錯誤「沒有匹配的函數調用arraySearch 」。前兩個函數對int數組和double數組的調用很好,好像我只是缺少處理字符串數組的詳細信息,我無法弄清楚它是什麼。無論如何,它必須是一個數組(無向量)。任何幫助將非常感激!傳遞字符串數組到模板的搜索功能

#include<iostream> 
#include<string> 

using namespace std; 

template<typename T> 
bool arraySearch(T array[], int size, T thing) 
{ 
    for(int i = 0; i < size; i++) 
    { 
      if(array[i] == thing) 
      return true; 
    } 

    return false; 
}   

int main() 
{ 
    const int SIZE = 12; 
    int intArray[] = {14, 3, 6, 76, 34, 22, 21, 54, 33, 23, 76, 234}; 
    cout << "The element was found: " << arraySearch(intArray, SIZE, 23) << endl; 

    double doubleArray[] = {34.5, 65.56, 11.1, 45.4, 87.5, 98.3, 23.6, 15.5, 3.3, 5.44, 54.3, 99.9}; 
    cout << "The element was found: " << arraySearch(doubleArray, SIZE, 23.6) << endl; 

    string stringArray[] = {"cool", "bug", "master", "katze", "republic", "randolph", "watermelon", "igloo", "sardine", "cream", "yellow", "rubber"}; 
    cout << "The element was found: " << arraySearch(stringArray, SIZE, "cool") << endl; 

system("pause"); 
return 0; 
}  
+0

模板與不安全的C風格的數組?來吧... – leftaroundabout 2013-04-21 18:53:40

+0

@leftaroundabout你能多說一點嗎? – user2302335 2013-04-21 19:13:30

+0

我的意思是,爲什麼不使用適當的C++容器,如'std :: array'或'std :: vector',而不是'T []'? – leftaroundabout 2013-04-21 19:36:40

回答

4

你需要說:

cout << "The element was found: " << arraySearch(stringArray, SIZE, std::string("cool")) << endl; 

的問題是,當模板與Tstd::string實例"cool"不是T一個實例。在C++中,字符串文字是C char數組,而不是std::string


此外,你可以簡單地使用std::find<algorithm>實現爲您發佈的代碼相同的效果。 std::find可以使用C數組和指針以及C++迭代器。

std::string* res = std::find(stringArray, stringArray + sizeof(stringArray)/sizeof(std::string), "cool"); 
+0

不錯!你的解釋是有道理的。 – user2302335 2013-04-21 18:58:48

3

的問題是,T被推斷爲是從第一個參數std::string,並從const char*第二個參數。

因此,編譯器不知道選擇哪一個。嘗試這樣做:

arraySearch(stringArray, SIZE, std::string("cool")) 

,或者,讓函數模板接受不同類型的參數:

template<typename T, typename U> 
bool arraySearch(T array[], int size, U thing) 

這不需要構建一個明確對象std::string

arraySearch(stringArray, SIZE, "cool") 

如果你決定採用這種方式,你可能想要進一步SFINAE-約束你的函數模板,以便它只接受類型相等的類型:

template<typename T, typename U, 
     decltype(declval<T>() == declval<U>())* = nullptr> 
bool arraySearch(T array[], int size, U thing)