473,748 Members | 2,891 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

"Reverse" polymorphism

Hi there,

I am having an interesting C++ problem which I currently am working
around but I don't like this so perhaps somebody has a better idea.

Basically I am parsing (rather: scanning) a specification (Word
document, ugh) and want to generate code from the information I gather,
mostly argument passing stuff.

The types I have to (un)marshal are currently represented by the
following (simplified) class hierarchy:

class Type { ... };
class ArrayType { ... };
class PointerType { ... };

When generating code I run into the problem to generate different code
depending on the class of the associated type object. Basically the
emitter would have to check the type of the parameter like this:

PointerType *ptr = dynamic_cast<Ar rayType*>(arg->type());
if (ptr != 0) { ... }

Obviously I don't like this. OTOH the Type classes don't know how to
generate code (I have to generate Java and C code, and maybe a
simplified C code for an embedded system).

For different outputs I have instances of the class CodeGenerator with
a generate method for each object I might have to generate code for:

class CodeGenerator {
public:
void generate(const ArrayType& t);
void generate(const PointerType& t);
...
};

Of course when calling the generate method passing some object
reference with the static type "Type" (which is an abstract class) I
get an error. I could work around this by adding a generate method for
a Type reference which could multiplex into the specialized methods.
But I don't like using explicit RTTI.

So what I did is to add a method with the following signature to the
Type class:

virtual void generate(CodeGe nerator &c) = 0;

which is implemented in each subclass like this:

void generate(CodeGe nerator &c) { c.generate(*thi s); }
So to generate code I have to write something like this:

CodeGenerator &cg = ...;
Type &t = ...; // some PointerType
t.generate(cg);

This works but it's a bit too much stuff for this small problem if you
ask me. Also adding the implementation of the generate method for each
type is boring and could lead to errors. This is no big deal in my
small project but I wonder how this problem could be solved more
elegantly.
Thanks for any hints, thoughts or comments

Torsten

Oct 1 '05 #1
2 2816
* Torsten Landschoff:
what I did is to add a method with the following signature to the
Type class:

virtual void generate(CodeGe nerator &c) = 0;

which is implemented in each subclass like this:

void generate(CodeGe nerator &c) { c.generate(*thi s); }
This is sound; it's the basic visitor pattern.

So to generate code I have to write something like this:

CodeGenerator &cg = ...;
Type &t = ...; // some PointerType
t.generate(cg);


Add a Type member function

void doAllTheGenerat eStuff()
{
CodeGenerator& cg = ...;
generate( cg );
}

If that isn't enough consider the template pattern to insert snippets of
derived class specific actions inside the above code; essentially that just
amounts to using virtual member functions for those actions. And/or pass as
argument an object that implements usage specific actions. There's almost no
problem in computer science that can't be solved by a bit of indirection.

--
A: Because it messes up the order in which people normally read text.
Q: Why is it such a bad thing?
A: Top-posting.
Q: What is the most annoying thing on usenet and in e-mail?
Oct 1 '05 #2

Torsten Landschoff wrote:
Hi there,

I am having an interesting C++ problem which I currently am working
around but I don't like this so perhaps somebody has a better idea.

Basically I am parsing (rather: scanning) a specification (Word
document, ugh) and want to generate code from the information I gather,
mostly argument passing stuff.

The types I have to (un)marshal are currently represented by the
following (simplified) class hierarchy:

class Type { ... };
class ArrayType { ... };
class PointerType { ... };

When generating code I run into the problem to generate different code
depending on the class of the associated type object. Basically the
emitter would have to check the type of the parameter like this:

PointerType *ptr = dynamic_cast<Ar rayType*>(arg->type());
if (ptr != 0) { ... }

Obviously I don't like this. OTOH the Type classes don't know how to
generate code (I have to generate Java and C code, and maybe a
simplified C code for an embedded system).

For different outputs I have instances of the class CodeGenerator with
a generate method for each object I might have to generate code for:

class CodeGenerator {
public:
void generate(const ArrayType& t);
void generate(const PointerType& t);
...
};

Of course when calling the generate method passing some object
reference with the static type "Type" (which is an abstract class) I
get an error. I could work around this by adding a generate method for
a Type reference which could multiplex into the specialized methods.
But I don't like using explicit RTTI.

So what I did is to add a method with the following signature to the
Type class:

virtual void generate(CodeGe nerator &c) = 0;

which is implemented in each subclass like this:

void generate(CodeGe nerator &c) { c.generate(*thi s); }
So to generate code I have to write something like this:

CodeGenerator &cg = ...;
Type &t = ...; // some PointerType
t.generate(cg);

This works but it's a bit too much stuff for this small problem if you
ask me. Also adding the implementation of the generate method for each
type is boring and could lead to errors. This is no big deal in my
small project but I wonder how this problem could be solved more
elegantly.
Thanks for any hints, thoughts or comments

Torsten


If I'm not mistaken, it sounds like you're trying to clone your derived
types.
If so, consider using a clone smart pointer, which can do this for you
automatically.
Check out the code in the following links:
http://code.axter.com/copy_ptr.h

http://code.axter.com/cow_ptr.h

For usage info, check out the following link:
http://www.codeguru.com/Cpp/Cpp/algo...le.php/c10407/

Oct 2 '05 #3

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

Similar topics

5
2191
by: Amir S. | last post by:
Hi, I'm a newbie to C++ (2 weeks into the course). We were given this assignment to write some code that reads a set of integers (grades) from a file (filename passed by console), outputs them in reverse order, calculates and prints their average. => We have been told that we need to make sure that our code meets "information hiding" guidelines. Could anyone help me get started with this (any ideas?)
14
2102
by: TTroy | last post by:
Hello, can anyone explain why the following function will not work for INT_MIN: /* itoa: convert n to characters in s */ void itoa(int n, char s) { int i, sign; if((sign = n) < 0) /* record sign */
8
7597
by: vijay | last post by:
Hello, As the subject suggests, I need to print the string in the reverse order. I made the following program: # include<stdio.h> struct llnode { char *info;
4
4221
by: Ollie | last post by:
I have wrriten a reverse proxy for a client of mine, this reverse proxy takes the url takes it attempt to access a *.XXXX and returns the the contents of an aspx web page from another internal server, the user then clicks on a button on the page that then posts data to the reverse proxy and it routes to the correct page by creating a web request and setting the method to post. (the reverse proxy is written using the IHttpHandler interface...
3
2951
by: Chen ShuSheng | last post by:
HI, I am now study a segment of codes: ------------------------ printf("%p\t",fp); /*add by me*/ fseek(fp, 0L, SEEK_END); /* go to end of file */ printf("%p\t",fp); /*add by me*/ last = ftell(fp); cout<<"last="<<last<<"\t"; /*add by me*/ -------------------------
32
14692
by: Licheng Fang | last post by:
Basically, the problem is this: 'do' Python's NFA regexp engine trys only the first option, and happily rests on that. There's another example: 'oneself' The Python regular expression engine doesn't exaust all the
3
1328
by: metaperl | last post by:
For this program: def reverse(data): for index in range(len(data)-1, -1, -1): yield data r = reverse("golf") for char in r: print char
8
4760
by: arnuld | last post by:
i have created a solutions myself. it compiles without any trouble and runs but it prints some strange characters. i am not able to find where is the trouble. --------------------------------- PROGRAMME -------------------------------- /* K&R2 section 1.9 exercise 1.19
1
15987
by: Rudolf Bargholz | last post by:
Hi, We have created triggers to log modifications to tables in our application. The triggers work fine, just on one of the tables in our database the triggers fail with the error message <SQL0437W Performance of this complex query may be sub-optimal. Reason code: "1". SQLSTATE=01602>. The same trigger on other tables works fine (the triggers are autogenerated with the same structure for most of the tables used in our application). I...
0
8987
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
8826
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
9366
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
0
8239
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...
1
6793
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6073
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
4597
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...
1
3303
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
3
2211
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.