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<ArrayType*>(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(CodeGenerator &c) = 0;
which is implemented in each subclass like this:
void generate(CodeGenerator &c) { c.generate(*this); }
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