简体   繁体   中英

make C++ treat unsigned char* as char*

I inherit c++ source files with lots of calls to x.append(p, len) , where x is of string type. However, in many cases, p is of type "unsigned char *" it caused lots of errors on my g++ (ver 4.8.4). If I manually change the p to (char*)p , it will work. But there are too many such instances (poor me!).

Wonder if there is a way to tell g++ just treat unsigned char* as char * .

Thanks.

UPDATE 1

The following code snippet will give an error when compiling with command line g++ -std=c++11 -fpermissive te1.cc . However, it actually compiles (fine but with a warning) when the type of variable len is changed from int to size_t . Unfortunately I can't change the type of the parameter, wonder if there is a way to tell compiler to just treat the second parameter as size_t when searching for a version of append() method.

//content of te1.cc
#include <iostream>

typedef unsigned char uchar;
using namespace std;
string x = "hi ";

int main(int argc, char *argv[]) {
    uchar *p = (uchar *)"tom";
    int len = 3;
    x.append(p, (size_t)len);
    cout << x << endl;
    return 0;
}

EDIT:

Extending c++ string class probably isn't a good idea ( see that question ).

I don't know in what contexts in your code the append method is used, but You may try to add type casts using your favorite editor and a simple regular expression:

Find pattern:

append\(([^,\)]+),([^\)]*)\);

Replace pattern:

append((char *)($1),$2);

See the small example I made.

Good grief! Don't hack stuff like that!

If you really must change the default signedness of char , use the proper GCC command-line option:

  • -funsigned-char
  • -fsigned-char

However, it would be better to simply fix the code to use the proper type at declaration, and deal with the (few) odd spots where something breaks.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM