常量字符* 作为模板的参数

const char* as argument to template

本文关键字:参数 字符 常量      更新时间:2023-10-16
/* Find an item in an array-like object
 * @param val the val to search for
 * @param arr an array-like object in which to search for the given value
 * @param size the size of the array-like object
 * @return the index of the val in the array if successful, -1 otherwise
 */
template < class T>
int mybsearch(T val, T const arr[], const int &size)

当我尝试使用 const char* 和字符串数组调用此模板函数时,编译器抱怨...mybsearch("peaches", svals, slen),我该如何修改模板原型以适应这种情况?

这是字符串数组

  string svals[] = { "hello", "goodbye", "Apple", "pumpkin", "peaches" };
  const int slen = sizeof(svals)/sizeof(string);

因为T被推导为const char*,所以您正在尝试使用string[]初始化const char* const[]。这是行不通的(数组只能在参数类型与参数类型基本相同的情况下传递给函数 - 除了限定符)。

你可以

  • 始终如一地使用 C 字符串,例如:

    const char* svals[] = { "hello", "goodbye", "Apple", "pumpkin", "peaches" };
    

    推荐。

  • 一致地使用C++字符串

    mybsearch(string("peaches"), svals, slen)
    
  • 将参数与 mybsearch 解耦(因此您可以搜索与数组类型不同的类型元素,只要它们是可比的)

    template < class T, class U>
    int mybsearch(T val, U const arr[], const int &size)
    

(问题扩展后完全更改了答案)

问题是你搜索的值是一个const char *,但你搜索的数组是一个std::string的数组。 (好吧,我希望你已经using std代码的某个地方,并且你使用的是标准字符串而不是你自己的字符串。

您需要像这样调用它:

mybsearch(string("peaches"), svals, slen)