C
chris.kemmerer
I am having a problem with templates and I hope someone here can help.
I am writing a library that accepts data packets, parses them and
saves the information for later use. One member of the packet is an
enumeration that says what type of data the packet contains (int,
char, etc.). I have created classes similar to below. The problem I am
having is in trying to access the derived class given only a pointer
to the base class. I know that the pointer I am reading from the
vector points to the appropriate derived class but I have no way of
knowing it's underlying data type before hand so I can't explicitly
declare a variable of the correct derived class. Any help is
appreciated even if it is a definitive "Can't do it".
Thanks,
Chris
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
I am writing a library that accepts data packets, parses them and
saves the information for later use. One member of the packet is an
enumeration that says what type of data the packet contains (int,
char, etc.). I have created classes similar to below. The problem I am
having is in trying to access the derived class given only a pointer
to the base class. I know that the pointer I am reading from the
vector points to the appropriate derived class but I have no way of
knowing it's underlying data type before hand so I can't explicitly
declare a variable of the correct derived class. Any help is
appreciated even if it is a definitive "Can't do it".
Thanks,
Chris
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