Ambiguous String_var operator

GCC is quite pedantic, so code like this can cause problems:

  CORBA::String_var s = ...
  s[0] += 1;

GCC 3.3 gives the following error (twice!):

file.cc:10: error: ISO C++ says that
  `char& _CORBA_String_var::operator[](long unsigned int)'
  and `operator[]' are ambiguous even though the worst 
  conversion for the former is better than the worst
  conversion for the latter

This has already been reported as a bug in GCC. However, the GCC people say that the error is correct, and the GCC bug was resolved by improving the diagnostic message.

So, what’s going on here?

Here’s a simple example that elicits the same error message:

  struct X {
    char& operator[](long i);
    operator char*();
    operator const char*() const;
  };
  
  void f(X &x)
  {
    x[0] += 1;
  }

x[0] is ambiguous, because it could be x.operator[](0) or static_cast<char *>(x)[0].

Unfortunately a CORBA::String_var contains exactly this ambiguity. The best solution is to explicitly disambiguate the call, by stating the type of the literal value:

  CORBA::String_var s = ...
  s[ CORBA::ULong(0) ] += 1;

This may not be pretty, but it’s the best way to get it to work.

Leave a Comment

Sponsors