Skip to main content
gamedev.net
🔒 Locked

Overloading Square Brackets

Started by Kustaz 1 reply 1.3k views
Original Post
Kustaz
Kustaz
Hey there. I'm trying to overload the square brackets, [], in a template function. Lets say, the container looks like this: container<class T> X { private: T *Data; }; assuming Data points to a dynamically allocated array, How would I correctly overload the square brackets, for template X, so that the following piece of code would assign the value 10 to elemenent 5 of Test, which is of type X: Test[5] = 10;
BeanDog
BeanDog
On a Google search for "C++ overload indexing operator", I found this page with the following snippet:
    //: C16:Array2.cpp    // Non-inline template definition    #include "../require.h"    template<class T>    class Array {      enum { size = 100 };      T A[size];    public:      T& operator[](int index);    };    template<class T>    T& Array<T>::operator[](int index) {      require(index >= 0 && index < size,        "Index out of range");      return A[index];    }    int main() {      Array<float> fa;      fa[0] = 1.414;    } ///:~


Cheers,
Kustaz
Kustaz
Thanks mate, I've got it working now. I'd just like to say that I did extensively google this question, I just wasn't too sure of the name of the operator(in this case, the "indexing operator"), thanks for the help!

Topic Locked

This topic has been locked by a moderator. New replies are not allowed.

Sign in to reply to this topic.