Global overload of type operator?

I am writing some kind of "portable" code (this means that it targets 32-bit and 64-bit MSVC2k10 and GCC on Linux), in which I am more or less:

typedef unsigned char uint8; 

C-strings are always uint8; this is for string processing purposes. The legacy char code is compiled as signed, so I cannot set the default value for unsigned compiler switches. But if I process the string, I cannot index the array very well:

 char foo[500]; char *ptr = (foo + 4); *ptr = some_array_that_normalizes_it[*ptr]; 

You cannot index an array with a negative number at runtime without serious consequences. Saving unsigned C-strings allows for such easier error protection.

I would really like not to leave casting (char *) every time I use a function that accepts char *, and also stops duplicating class functions so that they also execute. This is especially painful because the string constant is implicitly passed as char *

 int foo = strlen("Hello"); // "Hello" is passed as a char * 

I want all this to work:

 char foo[500] = "Hello!"; // Works uint8 foo2[500] = "Hello!"; // Works uint32 len = strlen(foo); // Works uint32 len2 = strlen(foo2); // Doesn't work uint32 len3 = strlen((char *)foo2); // Works 

There are probably warnings that allow you to use implicit type conversions of this kind, but it would be nice to use functions that take char * without casting every time.

So, I decided something like this would work:

 operator char* (const uint8* foo) { return (char *)foo; } 

However, it is not. I can’t understand how this works. I also cannot find anything to tell me why there seems to be no way to do this. I see a possible logic: implicit conversions like this can cause too many FAR errors, but I can’t find anything that says “it won’t work in C ++” or why or how to make it work (without waiting to make the uin8 class, which is ridiculous).

+6
source share
3 answers

I'm not a big fan of using the [ab] operator, but why do I need C ++?

You can do the following:

 const char* operator+(const uint8* foo) { return (const char *)foo; } char* operator+(uint8* foo) { return (char *)foo; } 

With certain, your example above:

 uint32 len2 = strlen(foo2); 

will become

 uint32 len2 = strlen(+foo2); 

This is not an automatic selection, but in this way you have a simple but explicit way to do it.

+1
source

The global transfer operator (typecast), the global assignment operator, the global array index operator, and the overload of the global function call operator are not allowed in C ++ .

MSVS C ++ will generate C2801 errors on them. Take a look at the wiki for a list of C ++ statements and overload rules.

+3
source

Both of the compilers you are talking about have a "handle unsigned character" switch. Why not use this?

0
source

Source: https://habr.com/ru/post/904275/


All Articles