Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

error: 'operator[]' is not defined

I'm having a problem compiling with g++ a fragment of my library that is related with the operator[].

I have recreated the same problem with this code:

    template<class A,class B> class X {
    public: 
        template<class C> X<C,B>& operator[]( const C& );
    };

    template<class A,class B,class C> class Y : public X<C,B> {
        friend X<C,B>& X<A,B>::template operator[]<C>( const C& );
    private:
        Y( X<A,B>& object , const C& index ) : X<C,B>() {};
    };

    template<class A,class B> template<class C> X<C,B>& X<A,B>::operator[]( const C& index ) {
        return *( new Y<A,B,C>( *this , index ) );
    }

    int main() {
        X<int,void> x;
        X<int,void>& y = x[2];
    }

g++ exits with the following error:

./src/test.cpp: In instantiation of ‘Y<int, void, int>’:
./src/test.cpp:14:   instantiated from ‘X<C, B>& X<A, B>::operator[](const C&) [with C = int, A = int, B = void]’
./src/test.cpp:19:   instantiated from here
./src/test.cpp:8: error: ‘operator[]’ not defined
./src/test.cpp: In member function ‘X<C, B>& X<A, B>::operator[](const C&) [with C = int, A = int, B = void]’:
./src/test.cpp:19:   instantiated from here
./src/test.cpp:10: error: ‘Y<A, B, C>::Y(X<A, B>&, const C&) [with A = int, B = void, C = int]’ is private
./src/test.cpp:14: error: within this context

I think that the problem is in the friend declaration of 'operator[]' in class Y, but I don't know where it is wrong. I tried searching myself, but can't find anything useful. Can anyone help me?

Thanks, Gianni

like image 737
Gianni Pisetta Avatar asked Aug 18 '11 10:08

Gianni Pisetta


1 Answers

Since you did not tell what your real design goal is, it is a bit difficult to propose something good, but at least using

template<class CC> friend X<CC,B>& X<A,B>::operator[]( const CC& );

as the friend declaration will make it compile, since that tells it to be a template.

Edit:

On a second thought, I think your code should work too, as it does not specify a specialization. Have you tried using clang to test it? It seems like a bug in gcc there...

like image 158
PlasmaHH Avatar answered Oct 19 '22 23:10

PlasmaHH