Re: Help getting to a derived class template given a pointer to a no-template base class
On Sep 26, 4:50 pm, "Victor Bazarov" <v.Abaza...@comAcast.net> wrote:
chris.kemme...@att.net wrote:
I am having a problem with templates and I hope someone here can help.
It's not a problem with templates. It's a problem with understanding
(or not understanding) how inheritance works, I'm afraid.
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.
"Similar"?
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; }
Bad idea to return by value. BTW, is this function declared 'private'
intentionally?
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
What are you trying to do? 'PacketBase' does not have 'Values'
member. Is that what your compiler is telling you? Well, it is
correct. Or is it telling you that the member is "unaccessible"?
Read the FAQ 5.8 and follow its recommendations.
V
--
Please remove capital 'A's when replying by e-mail
I do not respond to top-posted replies, please don't ask
I'm sorry, I was making up these classes to show the issue with as
little superfluous stuff as possible. The Values() functions is
declared public.
I am currently passing by value but that is not a requirement and I
can easily change it to pass by reference.
I know that PacketBase does not have a Values() function because it
can't, PacketBase doesn't know anything about the template type. I
could do away with all this indirection if UsePackets could hold a
vector of Packet class pointers but I didn't think that was possible
since Packet is a class template and each Packet instance can have a
different type.
Where do I find FAQ 5.8?
Thanks,
Chris