常量字符* 作为模板的参数
const char* as argument to template
/* 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)
相关文章:
- 带有指定长度字符* 参数的 std::regex_search 在 VS2017 中不起作用?
- 如何解决一元"*"(有"字符")错误的无效类型参数?
- OpenCL 内核参数中的字符***?
- 无法将参数 1 从 WCHAR 转换为常量字符 *
- 如何将常量字符*作为参数传递给LPCSTR参数?
- 从常量字符*、字符*参数到标准::字符串的直接转换接口
- 在 Windows 中使用 boost::p rogram_options 从命令行参数读取 Unicode 字符
- (C/C++)fscanf_s从txt文件以字符形式读取数组时缺少整数参数错误
- 通过像printf这样的可变参数函数传递一个带有常量字符*转换函数的类
- 如何将从第 2 个字符开始的字符串作为函数中的参数传递以进行递归,并约束数据 tiee 是函数中的字符串?
- 常量字符[] 默认函数参数
- 如何将二维数组类型字符(字符串)作为函数参数传递?
- 显式(布尔值)可以作用于字符文字参数的长度吗?
- 当C 中的系统调用conconculables时,参数字符串中的字符损失
- 字符串参数常量字符* 和常量 wchar_t*
- 为什么静态常量字符 * const 变量在为左值时可绑定到右值引用参数
- q致命参数:将 QString 转换为常量字符* 会导致警告"format string is not a string literal"
- std::string 参数是如何从原始字符数组文本传递的
- 将文本字符串作为常量字符 * 参数传递会导致代码分析器错误
- 可变参数字符列表的模板参数推导