c++ overload resolution and constness

Viewed 115

(all tests are performed on Microsoft (R) C/C++ Optimizing Compiler Version 19.00.24215.1 for x86)

consider this minimal example:

struct myString
{
    operator const char *( ) const { return &dummy; }
    char& operator[]( unsigned int ) { return dummy; }
    const char& operator[]( unsigned int ) const { return dummy; }

    char dummy;
};

int main()
{
    myString str;
    const char myChar = 'a';

    if( str[(int) 0] == myChar ) return 0; //error, multiple valid overloads
}

according to overload resolution rules (from cppreference)

F1 is determined to be a better function than F2 if implicit conversions for all arguments of F1 are not worse than the implicit conversions for all arguments of F2, and

1) there is at least one argument of F1 whose implicit conversion is better than the corresponding implicit conversion for that argument of F2

2) or. if not that, (only in context of non-class initialization by conversion), the standard conversion sequence from the return type of F1 to the type being initialized is better than the standard conversion sequence from the return type of F2

char& operator[]( unsigned int ) should be better, according to 1).

Of the two arguments (this = myString) do not need to be converted at all while operator const char *( ) const converts it to const char* and const char& operator[]( unsigned int ) const converts it to const myString, therefore there is one argument without any implicit conversion, which happens to be the best conversion

However my compiler yells the following error:

1>  [///]\sandbox\sandbox\sandbox.cpp(29): error C2666: 'myString::operator []': 3 overloads have similar conversions
1>  [///]\sandbox\sandbox\sandbox.cpp(19): note: could be 'const char &myString::operator [](unsigned int) const'
1>  [///]\sandbox\sandbox\sandbox.cpp(18): note: or       'char &myString::operator [](unsigned int)'
1>  [///]\sandbox\sandbox\sandbox.cpp(29): note: while trying to match the argument list '(myString, int)'

also note that using if( str[0u] == myChar ) return 0; or removing operator const char *( ) const resolve the error

why is there an error here and what am I getting wrong about overload resolution rules?

edit: it might be a visual C++ bug in this version, any definitive confirmation on this?

1 Answers
Related