473,770 Members | 6,133 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Help getting to a derived class template given a pointer to a no-template base class

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<typena me T>
class Packet : public PacketBase
{
std::vector<TVa lues() { return m_Values; }
std::vector<T m_Values;
...
};

class UsePackets
{
std::vector<Pac ketBase*m_Packe ts;
...
};

.... somewhere in the main code...
UsePackets foo;
foo.m_Packets.p ush_back(new Packet<int>);
foo.m_Packets.p ush_back(new Packet<short>);
PacketBase* packet = foo.m_Packets.a t(1);
packet->Values(); // can't access this function

Sep 26 '07 #1
6 1707
ch************@ 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<typena me T>
class Packet : public PacketBase
{
std::vector<TVa lues() { 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<Pac ketBase*m_Packe ts;
...
};

... somewhere in the main code...
UsePackets foo;
foo.m_Packets.p ush_back(new Packet<int>);
foo.m_Packets.p ush_back(new Packet<short>);
PacketBase* packet = foo.m_Packets.a t(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 "unaccessib le"?

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
Sep 26 '07 #2
On Sep 26, 4:50 pm, "Victor Bazarov" <v.Abaza...@com Acast.netwrote:
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<typena me T>
class Packet : public PacketBase
{
std::vector<TVa lues() { 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<Pac ketBase*m_Packe ts;
...
};
... somewhere in the main code...
UsePackets foo;
foo.m_Packets.p ush_back(new Packet<int>);
foo.m_Packets.p ush_back(new Packet<short>);
PacketBase* packet = foo.m_Packets.a t(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 "unaccessib le"?

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

Sep 26 '07 #3
ch************@ att.net wrote:
[..]
Where do I find FAQ 5.8?
See http://www.parashift.com/c++-faq-lite/ And "Where to I find
the FAQ for this newsgroup?" should be the first question you
ask when you walk in. Of course, you wouldn't have to do that
if you bothered to read the newsgroup for at least a day before
posting...

V
--
Please remove capital 'A's when replying by e-mail
I do not respond to top-posted replies, please don't ask
Sep 26 '07 #4
On Sep 26, 9:32 pm, chris.kemme...@ att.net wrote:
>
class PacketBase
{
virtual ~PacketBase() {}
...

};

template<typena me T>
class Packet : public PacketBase
{
std::vector<TVa lues() { return m_Values; }
std::vector<T m_Values;
...

};

class UsePackets
{
std::vector<Pac ketBase*m_Packe ts;
...

};

... somewhere in the main code...
UsePackets foo;
foo.m_Packets.p ush_back(new Packet<int>);
foo.m_Packets.p ush_back(new Packet<short>);
PacketBase* packet = foo.m_Packets.a t(1);
packet->Values(); // can't access this function
Would something like this work?

class PacketBase
{
virtual ~PacketBase() {}
virtual std::vector<boo st::any>& Values() const =0;
...

};

template<typena me T>
class Packet : public PacketBase
{
std::vector<boo st::any>& Values() const { return m_Values; }
std::vector<boo st::any m_Values;
...

};

class UsePackets
{
std::vector<Pac ketBase*m_Packe ts;
...

};

... somewhere in the main code...
UsePackets foo;
foo.m_Packets.p ush_back(new Packet<int>);
foo.m_Packets.p ush_back(new Packet<short>);
PacketBase* packet = foo.m_Packets.a t(1);
vector<boost::a nywoot = packet->Values();

You may also be able to wrap the vector itself in boost::any but I've
never done anything like that.

Saul

Sep 27 '07 #5
On Sep 27, 2:26 pm, chris.kemme...@ att.net wrote:
>
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(???).nam e T;
PacketBase* base = foo.m_Packets.a t(1);
Packet<T>* derived = dynamic_cast<Pa cket<T>*>(base) ;
The problem is ??? isn't an object, just an enumeration.
Sorry, I didn't previous realise that the original problem is actually
that you need to store different types in the same container. Its best
not to throw away the type information at all. One possible way is
using vector<boost::v ariant<int,shor t,etc to hold the packets along
with boost::static_v isitor when you want to process them.

Saul

Sep 27 '07 #6
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.
Couldn't you use dynamic_cast?
UsePackets foo;
foo.m_Packets.p ush_back(new Packet<int>);
foo.m_Packets.p ush_back(new Packet<short>);
PacketBase* packet = foo.m_Packets.a t(1);
packet->Values(); // can't access this function
Packet<int*pi = dynamic_cast< Packet<int>* >(packet);
if (pi) pi->Values();
else {
Packet<short*ps = dynamic_cast< Packet<short>* >(packet);
if (ps) ps->Values();
}

Not the nicest code and there's probably a far better way, but it is a
quick solution.

Cheers,
Adam.
Sep 28 '07 #7

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

0
3478
by: abcd | last post by:
kutthaense Secretary Djetvedehald H. Rumsfeld legai predicted eventual vicmadhlary in Iraq mariyu Afghmadhlaistmadhla, kaani jetvedehly after "a ljetvedehg, hard slog," mariyu vede legai pressed Pentagjetvedeh karuvificials madhla reachathe strategy in karkun campaign deshatinst terrorism. "mudivae maretu winning or losing karkun global varti jetvedeh terror?" Mr. Rumsfeld adugued in a recent memormariyuum. vede velli jetvedeh madhla...
4
2659
by: Orion | last post by:
Hi, This is kind of last minute, I have a day and a half left to figure this out. I'm working on a project using ms-sqlserver. We are creating a ticket sales system, as part of the system, I need to be able to do a search for specific tickets withing price ranges, different locations within the theaters, etc. etc. My problem is in the search one of the criteria is to search for a group of seats together. For example let's say...
16
4456
by: David Ford | last post by:
I have a macro that I use across the board for freeing ram. I'd like to clean up my code so I don't get these warnings. #define sfree(x) _internal_sfree((void **)&x) #define _internal_sfree(x) ({ if(x && *x) { free(*x); *x=NULL; } }) void somefunction() { char *x = malloc(10); int *y = malloc(10);
22
2057
by: Dave Cooke | last post by:
Hi I am very new to C. I am trying to figure out how to initialize a struct in my main program. The struct is declared in anouther header file like this... typedef struct ln { int key; int data; struct ln *next; } listNode, *listNodePtr; just to test in my main method I tried to initialize the
9
2355
by: santosh | last post by:
Hello all, I've put together a small program to count the number of characters and 'words' in a text file. The minimum length of a word, (in terms of no. of characters), as well as word delimiting characters can be specified on the command line. The default delimiting characters built into the program are space, newline, tab, carriage return, form feed, vertical tab, comma and null. If a 'u' or 'U' is specified as the last command line...
13
4655
by: ppateel | last post by:
Hi, I am new to c++ and I am converting a c program to c++. I changed malloc call to new and I am getting an exception violation. Here is the relevant piece of code. Compiler vc++ 7.0 (.Net 2003) SQLINTEGER nCols; SQLINTEGER cbColDataLength; PBYTE* pColumnData = NULL;
12
3885
by: gcary | last post by:
I am having trouble figuring out how to declare a pointer to an array of structures and initializing the pointer with a value. I've looked at older posts in this group, and tried a solution that looked sensible, but it didn't work right. Here is a simple example of what I'm trying to accomplish: // I have a hardware peripheral that I'm trying to access // that has two ports. Each port has 10 sequential // registers. Create a...
15
2581
by: Jay | last post by:
I have a multi threaded VB.NET application (4 threads) that I use to send text messages to many, many employees via system.timer at a 5 second interval. Basically, I look in a SQL table (queue) to determine who needs to receive the text message then send the message to the address. Only problem is, the employee may receive up to 4 of the same messages because each thread gets the recors then sends the message. I need somehow to prevent...
47
2887
by: Jo | last post by:
Hi there, I'm Jo and it's the first time I've posted here. I'm in process of creating a database at work and have come a little unstuck.....I'm a bit of a novice and wondered if anyone could help. I work in a library and send out dual language books to babies of dual or other nationality. The db is to be used for logging a range of book titles and numbers ordered and books sent out to individuals. I am trying to work out a way of...
14
2746
by: pgfdbug | last post by:
First I am learning this as I go so please forgive my ignorance, all is self taught. I was given this as program to run an LED signboard for my fire station. The program is supposed to transmit the calls to the signboard so we can see what piece is due to go out the door. The problem is I am getting several warnings and also the program is sending multi-colors instead of just one. Any help is greatly appreciated. betabrite.c In...
0
9425
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10231
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
9871
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
8887
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
5313
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
5452
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
3972
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
3576
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2817
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.