funny syntax

I found an unintended ambiguity when I override the following operators in the class

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
class MyClass {
public:
	operator long() const;
	MyClass& operator[](const std::string& key) {
		return *this;
	}
};

void Func() {
	MyClass myCls;
	std::string key = "abc";
	myCls.operator[]("abc");
	myCls[key];
	myCls["abc"];  <-- complains about that more than one operator[] matches the operand (see full message below)
	123["abc"];  <-- this does nothing, but apparently this syntax is one of the option that caused the above
}


It complains about "more than one operator "[]" matches these operands:
built-in operator "integer[pointer-to-object]"
function "MyClass::operator[](const std::string& key)"
operand types are: MyClass [ const char[4]]

The error does go away if I add an additional
1
2
3
	MyClass& operator[](const char* key) {
		return *this;
	}


So basically it seems that the compiler accepts the form (integer[void*]) (see line 15). What does this syntax do and mean?
When x and y are respectively an integer and a pointer, x[y] is equivalent to *(x+y) is equivalent to *(y+x) is equivalent to y[x]. So 123["abc"] is equivalent to "abc"[123]. Basically an overflow of a static buffer.

Since MyClass is implicitly convertible to an integer type, myCls["abc"] can be ambiguously interpreted as "abc"[(long)myCls] or as myCls.operator[]("abc").
Topic archived. No new replies allowed.