Search code examples
c++classoperator-overloadingambiguous

C++ compilation error, ambigous operator overloads


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


Solution

  • 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.