 |
C++Talk.NET C++ language newsgroups
|
| View previous topic :: View next topic |
| Author |
Message |
Guest
|
Posted: Mon Jul 17, 2006 9:11 am Post subject: templates with virutal functions |
|
|
Hi!
I have a situation (described below) and my lack of expertise has
forced me to fabricate a not so good solution for it. I was thinking if
the experts here can help me.
Situation:
class Base {
int id;
}
class Derived : public Base {
int yid;
}
class X {
MyVector<Base> *base_vector;
};
class Y : public X {
MyVector<Derived> *derived_vector;
}
Now, in the above scenario, both derived_vector and base_vector point
to the same object and according to the design the base_vector can
contain objects of type base, but if we have Y's object then it
should only contain derived objects. i.e. base_vector is allowed to
contain objects of derived type only.
For this, I was thinking of exposing a virtual getter function in the X
class which returns MyVector<Base>* and overriding it in the derived
class to return MyVector<Derived>*. But since the two template
instantiations are not related to each other, I am not allowed to do
it.
If I do not do this, I am not able to think of a solution which will
provide me compile time check and disallow Base objects to be inserted
into objects of type Y.
Any help is highly appreciated.
Thanks,
Sudhanshu |
|
| Back to top |
|
 |
Vikram Guest
|
Posted: Mon Jul 17, 2006 9:11 am Post subject: Re: templates with virutal functions |
|
|
| Quote: | class Base {
int id;
}
class Derived : public Base {
int yid;
}
class X {
MyVector<Base> *base_vector;
};
class Y : public X {
MyVector<Derived> *derived_vector;
}
Now, in the above scenario, both derived_vector and base_vector point
to the same object
|
Not sure I understand this..why do they point to the same object?
| Quote: | and according to the design the base_vector can
contain objects of type base, but if we have Y's object then it
should only contain derived objects. i.e. base_vector is allowed to
contain objects of derived type only.
For this, I was thinking of exposing a virtual getter function in the X
class which returns MyVector<Base>* and overriding it in the derived
class to return MyVector<Derived>*. But since the two template
instantiations are not related to each other, I am not allowed to do
it.
|
Why not use a vector of base pointers rather than objects directly?
MyVector<Base*> some_vector;
Of course, then you will have to delete the objects in the vector in
your destructor. |
|
| Back to top |
|
 |
|
|
You cannot post new topics in this forum You cannot reply to topics in this forum You cannot edit your posts in this forum You cannot delete your posts in this forum You cannot vote in polls in this forum
|
|