0
class obj1{
public:
    void do(){}
    void some(){}
    void stuff(){}
};
class obj2{
public:
    void nowDo(){}
    void someOther(){}
    void things(){}
};

template <class T>
class structure{
public:
    /*
    access public members of Ts's elements while encapsulating the vector
    (preferably without copying all of obj's public members in the structure)
    */

private:
    vector <T *> Ts;
};

void foo(){
    structure <obj1 *> str1;
    structure <obj2 *> str2;
    /*
    Access public members of str1 and str2's elements 
    */
}

Is there a means by which I can access the public members of the 'obj' elements while encapsulating its vector within the 'structure' template class?

I would prefer to do so without copying all of the 'obj' public members in 'structure', because I want 'structure' to be a homogenized template class, that way I don't need to create a unique data structure for every object I want to contain.

1 Answers1

0

What about this?

template <class T>
class structure{
public:

    size_t getCount()
    {
         return Ts.size();
    }

    T& getItem(size_t index)
    {
        return Ts[index];
    }

private:
    vector <T> Ts; // notice the change I made here.
};

Then later in your code, you can just say this:

structure <obj1 *> str1;
size_t count = str1.getCount();
for (size_t i = 0; i < count; i++)
{
    str1->getItem(i)->Do();
    str1->getItem(i)->Some();
    str1->getItem(i)->Stuff();
}
selbie
  • 100,020
  • 15
  • 103
  • 173