Re: Help getting to a derived class template given a pointer to a no-template base class
On Sep 27, 5:36 am, shaz...@gmail.com wrote:
On Sep 26, 9:32 pm, chris.kemme...@att.net wrote:
class PacketBase
{
virtual ~PacketBase() {}
...
};
template<typename T>
class Packet : public PacketBase
{
std::vector<T> Values() { return m_Values; }
std::vector<T> m_Values;
...
};
class UsePackets
{
std::vector<PacketBase*> m_Packets;
...
};
... somewhere in the main code...
UsePackets foo;
foo.m_Packets.push_back(new Packet<int>);
foo.m_Packets.push_back(new Packet<short>);
PacketBase* packet = foo.m_Packets.at(1);
packet->Values(); // can't access this function
Would something like this work?
class PacketBase
{
virtual ~PacketBase() {}
virtual std::vector<boost::any>& Values() const =0;
...
};
template<typename T>
class Packet : public PacketBase
{
std::vector<boost::any>& Values() const { return m_Values; }
std::vector<boost::any> m_Values;
...
};
class UsePackets
{
std::vector<PacketBase*> m_Packets;
...
};
... somewhere in the main code...
UsePackets foo;
foo.m_Packets.push_back(new Packet<int>);
foo.m_Packets.push_back(new Packet<short>);
PacketBase* packet = foo.m_Packets.at(1);
vector<boost::any> woot = packet->Values();
You may also be able to wrap the vector itself in boost::any but I've
never done anything like that.
Saul- Hide quoted text -
- Show quoted text -
Thank your that idea. I usually don't like to use non-standard
libraries in order to keep my code as portable, and standards based as
possible but I recently attended some classes where Boost was featured
and it looked like it had some very usefull features.
A related question that may actually solve my first problem. The real
issue is being able to create a type from the enumeration I get from
the data packet. If I could somehow morph that into a usable typename
I could dynamically cast the base pointer to the proper derived
template. Something of the form:
typedef typeid(???).name T;
PacketBase* base = foo.m_Packets.at(1);
Packet<T>* derived = dynamic_cast<Packet<T>*>(base);
The problem is ??? isn't an object, just an enumeration.
Another way is if I can somehow pass the type up from the derived
class template to the base class.
In the mean time I'll look into Boost::Any.
Thank you.