Consider the following class:
class Test
{
public:
Test( char );
Test( int );
operator const char*();
int operator[]( unsigned int );
};
When I use it:
Test t;
Test& t2 = t[0];
I get a compiler error where it can’t figure out which operator[] to use. MSVC and Gcc both. Different errors. But same problem.
I know what is happening. It can construct a Test from either an int or a char, and it can either use Test::operator[] or it can cast to const char* and use the built char*[].
I’d like it to prefer Test::operator[].
Is there a way to specify a preference like this?
UPDATE: First, I’ll agree with response below that there is no language feature that lets you specify a priority for conversions. But like juanchopanza found below – you can create such a preference indirectly by making one conversion require no casts, and make the other require a cast. E.g. unsigned int as the argument for operator[] won’t work but, using int will.
The default index argument is unsigned – for gcc and msvc anyway – so making the index argument unsigned will cause the compiler to prefer the right operator.
@Konrad: about implicit conversions to built-in types. Agree generally. But I need it in this case.
No there isn’t. And this kind of ambiguity is why automatic conversions to another type (like
operator char*) are not recommended.