But wait, there's more. Here's the real problem. I also want to create a Copy() method that will copy this expression and its subexpressions. Something like:
Code:
Expression *
Expression::Copy (
Expression *parent)
{
Expression *copy;
int i, n;
copy = ???? (parent);
n = OpTerm ();
for (i = 0; i < n; i++)
copy->sub_exp[i] = sub_exp[i]->Copy (copy);
return copy;
}
The problem is what to put in the "???" part. How do I call the constructor for actual class implementing the abstract class. I conclude that I can't do it directly, but I'm hoping there's some technique for getting at it.
My first attempt was to declare an Alloc(parent) method on the Expression class. Then in the subclasses I would do:
Code:
class ExpAdd : public Expression
{
public:
ExpAdd (Expression *parent) : Expression (parent) {}
Expression * Alloc (Expression *parent)
{
return ExpAdd (parent);
}
...
};
The problem is I then have to do this same thing in every single subclass. There are dozens of operator types -- that's a lot of duplicated code. Is there a way to use a template to get rid of the noxious bit of boilerplate?