将字符串数组传递给模板化搜索函数

Passing a string array to templated search function

本文关键字:搜索 函数 字符串 数组      更新时间:2023-10-16

在下面的代码中,我试图搜索一个字符串数组,我传递给一个特定字符串的模板函数,但我得到错误"没有匹配的函数调用' 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;
}    

你需要说:

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

问题是"cool"不是T的实例,当模板被T实例化为std::string时。在c++中,字符串字面值是C字符数组,而不是std::string


同样,您可以简单地使用<algorithm>中的std::find来达到与您发布的代码相同的效果。std::find可以使用C数组和指针,也可以使用c++迭代器。

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

问题是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)