borabut
borabut

Reputation: 27

No such operator "[]" matches these operands

I am trying to make a program that demonstrates use of templates and overloaded operators for my CS class. Here is relevant code:

main:

    ArrayTemplate<int> number(0);
            number[0] = 1;
            number[1] = 2;
            number[2] = 3;

    ArrayTemplate<string> word("na");
            word[0] = "One";
            word[1] = "Two";
            word[2] = "Three";

header:

template<class T>
T& operator [](const int index) 
{ 
    if(index >= 0 && index < ARRAY_MAX_SIZE)
        return items[index];
    else
    {
        cerr << "INDEX OUT OF BOUNDS!!!";
        exit(1);
    }
}

The problem is that when I try to use my overloaded subscript operator I get the error message shown in title: "No such operator "[]" matches these operands" Im not exactly sure why. It does it for both my integer array and my string array. Any help is appreciated.

Upvotes: 0

Views: 11090

Answers (2)

Potatoswatter
Potatoswatter

Reputation: 137780

template<class T>
T& operator [](const int index) 

This declaration would be called e.g. as object.operator[] < type >( 5 ). Note that type needs to be provided as a template argument. Because there's no way to supply such an argument in an expression using [], the operator overload doesn't work.

Probably you don't want the template< class T > at all. Just get rid of it:

T& operator [](const int index) 

If you define the function outside the class {} scope, then it would look like this:

template<class T>
T& ArrayTemplate<T>::operator [](const int index) 

In this case, the template<class T> line re-introduces the parameter in order to get back into the class template.

Upvotes: 1

Pubby
Pubby

Reputation: 53037

You really need to show the full definition of ArrayTemplate.

This is how you probably want it to look:

template<class T>
class ArrayTemplate {
  public:

    // ...

    T& operator [](const int index) 
    { 
        if(index >= 0 && index < ARRAY_MAX_SIZE)
            return items[index];
        else
        {
            cerr << "INDEX OUT OF BOUNDS!!!";
            exit(1);
        }
    }

    // ...
};

Note that operator[] isn't templated; only the class is.

With your current code you would have to do it like this:

number<int>[0] = 1;
number<int>[1] = 2;
number<int>[2] = 3;

Which obviously goes against your intention.

Upvotes: 6

Related Questions