C++ compilation error, ambigous operator overloads

107 views Asked by At

I have a template array class overloading both operator [] to access items and operator T * to get direct buffer access.

template< typename T > class buffer
{
    const T & operator [] ( size_t ) const;
          T & operator [] ( size_t );

    operator const T * () const;
    operator       T * ();
};

For some reason, using operator [] on an instance of this class generates a compilation error saying that there is 4 possible overloads.

buffer< int > buf;
buf[ some_position ] = 0; // Generates an error

Error :

Error   3   error C2666: 'XXX::buffer<T>::operator []' : 4 overloads have similar conversions   c:\XXX.cpp  3886

Is the operator [] trying to convert my instance buf to a T * ? Why are 4 overloads detected instead of 2 ? Thank you. :)

EDIT : Actually it is : buf[ some_position ] = 0; // Generates an error

2

There are 2 answers

4
TartanLlama On BEST ANSWER

The issue is that you have implicit conversions going in both directions.

Disregarding const, your two candidates are:

T & buffer::operator [] ( size_t );
int& operator[] (int*, int);

For the call buf[pos] where pos is an int (such as a literal), the call is ambiguous. The first candidate could be selected by converting pos to a std::size_t and the second could be selected by converting buf to int*.

You could disambiguate this call by explicitly casting the argument to a std::size_t, or modifying the operator to take an int instead.

4
NathanOliver On

The Problem you are having is that operator T* and operator[] both will allow buf[some_position] to be valid. In your code T* is an int* and int* has an [] overload.

You can see that with this live example

I think this might be an issue with you VS as running the code on Coliru and ideone with some modifications to get it to run both give working code.