Overloading a function for char* and int - ambiguity error

For complex reasons that don't affect the problem, I have a type that needs to overload operator[] for both string literals and ints.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
class foo
{ public:
	operator[](std::string)
	operator[](int);
	operator[](char *);
}

...

foo x;

x["hi"];	// ok
x[4];		// ok
x[0];		// ambiguity error, 0 is a pointer and an int 


I don't want 0 to be a pointer in this case, but I don't want to have to use any special casts or conversions when using this operator. Is there any way to do this? I've tried to find one without any luck.

If I delete the char* operator[] then I can say (for example) x[string("hi"] but I'm trying to avoid that.
Just did a quick test both in mingw and msvc and I didn't get any ambiguity with 0.
The int version was selected.
Figured it out. I accidentally omitted from my writeup what turns out to be the key problem.

I declared the operator[](int) as unsigned int (because it's an error to pass a negative index to this function).

That was apparently the problem: int literals are of type "int", but the function was expecting an "unsigned int". This problem seemed strange to me, because C++ isn't supposed to use a conversion when the types exactly match. I'd forgotten that "unsigned int" and "int" aren't the same type, so when it went hunting, the compiler found both matches.

It works for me now (when I use plain old 'int' as my argument type). Thanks for the help.
Topic archived. No new replies allowed.