0

I have a class or struct, lets say, Container, with the following structure:

template <typename type> struct Container {
    vector <type *> v;
    ...
    functions
    ...
    type* operator[] (int i) { // not sure about this
          return (v)[i];
    }
};

where type can be a standard type or a custom defined class or struct.

This struct is supposed to work like this:

Container<type> * c(10);
c->function(); // calls a function that iterates over the elements of v

If I want to access individual elements of the vector, I can call

c->v[0]->function()

where function is a member of the type class; This works like expected; however, it could be simplified to

c[0]->function()

since the [] operator, as defined by me, would return a pointer to the contained class and not the container itself, but the compiler still complains that the container class has no member called "function". This is not a big issue, as can be easily avoided with a different syntax, but makes me think that I have some fundamental misunderstanding on how pointers and references works. What would be a proper way to define the [] operator here and what am I missing? Thank you in advance

EDIT: I edited the question to reflect my actual code

user3556781
  • 128
  • 6

1 Answers1

0

Your operator[] seems to be fine. You do seem to be missing a semi-colon after the name your struct.

Yes. The compiler tells me that Container has no member function, not type.

Did you define a function for Container then?

Here is a compiling, working example:

#include <iostream>
#include <vector>

struct A
{
    void Function () {
        std::cout << "A::Function()" "\n" ;
    }
};

template <typename type> struct Container {
    std::vector <type *> v;

    void Function () {
        std::cout << "Container::Function ()" "\n" ;
    }

    type* operator[] (int i) { 
          return (v)[i];
    }
};

int main (void)
{
    A a ;

    Container <A> c ;

    c.Function () ;

    c.v.push_back (&a) ;
    c[0]->Function () ;

    return 0 ;
}

Output:

Container::Function ()
A::Function()

Update

Here's an example of using a pointer.

int main (void)
{
    A a ;

    Container <A> *pC = new Container <A> ;

    pC->Function () ;

    pC->v.push_back (&a) ;
    (*pC) [0]->Function () ;

    delete pC ;

    return 0 ;
}

Of course, you should never have to use a raw pointer like this. You could use smart pointers instead or you can wrap your memory into a class for RAII.

Community
  • 1
  • 1
jliv902
  • 1,648
  • 1
  • 12
  • 21