gpt4 book ai didi

c++ - const char* 作为模板的参数

转载 作者:行者123 更新时间:2023-11-28 03:35:54 28 4
gpt4 key购买 nike

/* 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),我该如何修改模板原型(prototype)来适应这个?

这里是字符串数组

  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)

关于c++ - const char* 作为模板的参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10873829/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com