我正在尝试将 C 代码库编译为 C++,调整一些包含。它用于strchr()
无符号字符指针,例如:
#include <string.h>
#include <stdio.h>
// Cannot modify this file with any non-C-isms, but let's say an include can
// be changed (although all things being equal I'd rather not)
#include <SomethingICanChange.h>
int main(int argc, char* argv[]) {
unsigned char b = 'B';
unsigned char const * str = "ABC";
unsigned char const * pos = strchr(str, b);
if (pos) {
printf("position is %d\n", pos - str);
}
return 0;
}
这会导致 C++ 中的错误(原因在别处解释)......即使使用-fpermissive
.
test.c: In function ‘int main(int, char**)’:
test.c:6:33: warning: invalid conversion from ‘const char*’ to ‘const unsigned char*’ [-fpermissive]
test.c:7:46: error: call of overloaded ‘strchr(const unsigned char*&, unsigned char&)’ is ambiguous
test.c:7:46: note: candidates are:
In file included from test.c:1:0:
/usr/include/string.h:215:14: note: char* strchr(char*, int) <near match>
/usr/include/string.h:215:14: note: no known conversion for argument 1 from ‘const unsigned char*’ to ‘char*’
/usr/include/string.h:217:22: note: const char* strchr(const char*, int) <near match>
/usr/include/string.h:217:22: note: no known conversion for argument 1 from ‘const unsigned char*’ to ‘const char*’
通常当面对这种事情时,我会说“strchr, yuck, just get rid of it fully”。但我不想自己修改这些文件,这是 C 代码,它被保持在相当旧的平台上的可移植性。他们不会乐于在调用站点进行强制转换以安抚 C++……尽管如果“结构”存在并且是标准的,他们可能会使用它。
我也可以以一种或另一种方式破解它,就像SomethingICanChange.h
我可以添加:
unsigned char const * strchr(unsigned char const * s, int c) {
return (unsigned char const *)strchr((char const *)s, c);
}
这适用于-fpermissive
. 但是我无法将这种重载检查到 C 代码库中(好吧,没有#ifdef)。struchr
只是想知道是否有人有更好的想法,如果这就是这种情况下的人们最终会做的事情(或者如果有一个共同的名字,那么任何常见的名字),我会补充。