Overloading operator[] problem

From: Rui Maciel (rui_maciel_at_mail.com)
Date: 07/30/04


Date: Thu, 29 Jul 2004 23:47:14 +0000

I'm trying to write a small matrix and vector library but while I was
doing the operator overloading part, I've stumbled on an annoying
compiler error. My guess is that my operator[] is broken but I'm not
shure. I've googled for it but unfortunately it seems that the search
engine ignores the "[]" string and all the results I got were somewhat
vague and apparently unrelated.

So, can anyone help me on this one? Here are a few code snippets which
are related to the problem and the error message.

<declaration>
<filename=cVector.hpp>

(...)

class cVector
{
        private:
                std::vector<T> data;

        public:
                (...)
                T& operator[](unsigned int index);
                (...)
};

(...)

<filename=utils.hpp>

(...)

template <class T>
void printh(const cVector<T> v)

(...)

</declaration>

<implementation>
<filename=cVector.hpp>

(...)

template <class T>
T& cVector<T>::operator[](unsigned int index)
{
        return this->data[index];
}

(...)

<file=utils.hpp>

(...)

template <class T>
void printh(const cVector<T> v)
{
        using namespace std;
        cout << "[ " << v[0];
        for(unsigned int i = 1; i < v.dimension(); i++)
        {
                cout << ", " << v[i];
        }
        cout << " ]" << endl;
}
(...)
</implementation>

<compiler error message>

(...)

g++ -Wall -ansi -pedantic -c main.cpp
utils.hpp: In function `void mmvp::printh(mmvp::cVector<T>) [with T =
float]':
main.cpp:18: instantiated from here
utils.hpp:16: error: no match for 'operator[]' in 'v[0]'
cVector.hpp:90: error: candidates are: T&
mmvp::cVector<T>::operator[](unsigned int) [with T = float] <near match>
utils.hpp:19: error: no match for 'operator[]' in 'v[i]'
cVector.hpp:90: error: candidates are: T&
mmvp::cVector<T>::operator[](unsigned int) [with T = float] <near match>
make: *** [main.o] Error 1

(...)

</compiler error message>

Thanks in advance
Rui Maciel