How to avoid the `operator [] (const char *)` ambiguity?

Consider the following code:

class DictionaryRef {
public:    
  operator bool() const;
  std::string const& operator[](char const* name) const;

  // other stuff
};

int main() {
  DictionaryRef dict;
  char text[256] = "Hello World!";

  std::cout << dict[text] << std::endl;
}

      

When compiling with G ++, the following warning is issued:

warning: ISO C++ says that these are ambiguous, even though the worst conversion for the first is better than the worst conversion for the second:
note: candidate 1: const string& DictionaryRef::operator[](const char*) const
note: candidate 2: operator[](long int, char*) <built-in>

      

I know what this means (and the reason was explained in operator [] (const char *) ambiguity ), but I am looking for a way to provide the correct behavior / resolve the warning without changing My class design - since it makes sense for a class to have both a boolean conversion, so and operator [](const char*)

.

What is the purpose operator[](long int, char*)

besides generating random compiler warnings? I can't imagine anyone writing 1["hello"]

in real code.

+4


source to share


1 answer


While you "can't imagine someone writing 1["hello"]

in real code," this is something legitimate C ++ as a consequence of commutative []

inherited from C. It is reasonable or not how a language is defined and is unlikely to change for us.

The best way to avoid ambiguity is to add explicit

to boolean conversion - it's very rare that we ever want the implicit operator bool()

.



An alternative is to replace operator bool()

with operator void*()

, which will still satisfy boolean tests, but not convert to integer.

0


source







All Articles