Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing an "unsigned char" to an overloaded function expecting either char or const char* results in ambiguity

Tags:

c++

qt

I'm using a QByteArray to store raw binary data. To store the data I use QByteArray's append function.

I like using unsigned chars to represent bytes since I think 255 is easier to interpret than -1. However, when I try to append a zero-valued byte to a QByteArray as follows:

command.append( (unsigned char) 0x00));

the compiler complains with call of overloaded append(unsigned char) is ambiguous. As I understand it this is because a zero can be interpreted as a null pointer, but why doesn't the compiler treat the unsigned char as a char, rather than wondering if it's a const char*? I would understand if the compiler complained about command.append(0) without any casting, of course.

like image 800
SharpHawk Avatar asked Feb 19 '23 08:02

SharpHawk


2 Answers

Both overloads require a type conversion - one from unsigned char to char, the other from unsigned char to const char *. The compiler doesn't try to judge which one is better, it just tells you to make it explicit. If one were an exact match it would be used:

command.append( (char) 0x00));
like image 105
Mark Ransom Avatar answered Apr 09 '23 00:04

Mark Ransom


unsigned char and char are two different, yet convertible types. unsigned char and const char * also are two different types, also convertible in this specific case. This means that neither of your overloaded functions is an exact match for the argument, yet in both cases the arguments are convertible to the parameter types. From the language point of view both functions are equally good candidates for the call. Hence the ambiguity.

You seem to believe that the unsigned char version should be considered a "better" match. But the language disagrees with you.

It is true that in this case the ambiguity stems from the fact that (unsigned char) 0x00 is a valid null-pointer constant. You can work around the problem by introducing an intermediate variable

unsigned char c = 0x0;
command.append(c);

c does not qualify as null-pointer constant, which eliminates the ambiguity. Although, as @David Rodríguez - dribeas noted in the comments you can eliminate the ambiguity by simply casting your zero to char instead of unsigned char.

like image 22
AnT Avatar answered Apr 09 '23 00:04

AnT