HP aC++/HP C A.06.25 Programmer's Guide

Overload Resolution Ambiguity of Subscripting Operator
HP C++ and HP aC++ have different overload resolution models. When you migrate
to HP aC++, you may see an overload resolution ambiguity for the subscripting operator.
The following code illustrates the problem:
struct String {
char& operator[](unsigned);
operator char*();
// ...
};
void f(String &s) {
s[0] = 0;
}
HP C++ accepts the above code, selecting String::operator[](unsigned) rather
than the user-defined conversion, String::operator char*(), followed by the
built-in operator[].
Compiling the code with HP aC++ produces the following error:
Error 225: c.C, line 8 # Ambiguous overloaded function call;
more than one acceptable function found. Two such functions
that matched were char &String::operator [](unsigned int)
[c.C, line 2] and char &operator [](char *,int)
[Built-in operator].
s[0] = 0;
The error message appears because the compiler cannot choose between:
1. Not converting s, but converting 0 from type int to type unsigned int; this
implies using the user- provided subscript operator[]
2. Converting s to type char* (using the user-defined conversion operator), but not
converting 0; this corresponds to using the built-in subscript operator[].
In order to disambiguate this situation in favor of the user-provided subscript
operator[], make the conversion of 0 in alternative (1.) no worse
1
than the conversion
of 0 in alternative (2.).
Because the subscript type for the built-in operator[] is ptrdiff_t (as defined in
<stddef.h>), this is also the type that should be used for user-defined subscript
operators. Replace the previous example by:
#include <stddef.h>
struct String {
char& operator[](ptrdiff_t);
operator char*();
// ...
};
1. worse is relative to a ranking of conversions as described in the ANSI/ISO C++ International Standard on
overloading. In general, a user-defined conversion is worse than a standard conversion, which in turn
is worse than no conversion at all. The complete rules are more fine grained.
276 Migrating from HP C++ (cfront) to HP aC++