RWCString::operator[] doesn't compile in MSVC

Article ID: 897
Last updated: 05 Feb, 2008
Article ID: 897
Last updated: 05 Feb, 2008
Revision: 1
Views: 3684
Posted: 30 Jan, 1998
by Dean J.
Updated: 05 Feb, 2008
by Dean J.
Problem


When I try to compile RWCString's operator[] in MSVC

    RWCString str("Hello World."); cout<< str[3];

I get the error error C2666 : 2 overloads have similar conversions.

 




Cause


In MSVC, RWCString::operator[] is viewed as the global function
    char operator[](RWCString, size_t)

A call to str[3] is processed as a call to

    char operator[](RWCString, int)

Because there is not an exact match for this function call, the compiler attempts to find a match by using implicit typecasting. The match that we expect:

    char operator[](RWCString, size_t)

requires a single typecast from an int to a size_t.

RWCStrings can be typecast into char* by the operator

    RWCString::operator const char*() const

Using this typecast, the compiler can also interpret str[3] as

    char operator[](char*, int)

through one implicit typecast from an RWCString to a char*. It isn't clear to the compiler which function is best, so it returns the error.


Action


There are two recommended fixes to this problem.

  1. Always call str[] with an explicit typecast.
      str[(size_t) 3]
  2. Never require implicit typecasting
      size_t index;
      str[index];

These fixes should work in most situations. If the recommended fixes are unacceptable, insert this block of code into your RWCString class definition inside of rw/cstring.h.

inline char operator[](int i)
{
return operator[]((size_t) I);
}
This article was:   Helpful | Not helpful
Report an issue
Article ID: 897
Last updated: 05 Feb, 2008
Revision: 1
Views: 3684
Posted: 30 Jan, 1998 by Dean J.
Updated: 05 Feb, 2008 by Dean J.

Others in this category