2013-04-21 86 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)