This is a question related to homework. Basically I have to realize a scientific calculator.
Suppose that simplified code / hierarchy which represents a literal :
struct Literal {
virtual std::string toString() const = 0;
};
struct NumericLiteral : public Literal {};
struct IntegerLiteral : public NumericLiteral {
int value;
IntegerLiteral(int value) : value(value) {}
std::string toString() const override { return std::to_string(value); }
};
struct RationalLiteral : public NumericLiteral {
int num, den;
RationalLiteral(int den, int num) : num(num), den(den) {}
RationalLiteral(IntegerLiteral il) : num(il.value), den(1) {}
std::string toString() const override { return std::to_string(num) + '/' + std::to_string(den); }
};
struct RealLiteral : public NumericLiteral {
double value;
RealLiteral(double value) : value(value) {}
RealLiteral(IntegerLiteral il) : value(il.value) {}
RealLiteral(RationalLiteral rl) : value(rl.num / (double)rl.den) {}
std::string toString() const override { return std::to_string(value); }
};
struct ExpressionLiteral : public Literal {
std::string expr;
ExpressionLiteral() {}
ExpressionLiteral(std::string expr) : expr(expr) {}
ExpressionLiteral(IntegerLiteral nl) : expr(nl.toString()) {}
ExpressionLiteral(RationalLiteral rl) : expr(rl.toString()) {}
ExpressionLiteral(RealLiteral rl) : expr(rl.toString()) {}
std::string toString() const override { return expr; }
};
As you can see, there is conversion constructor from the less general literals to the more general literals, e.g. Integer to Real.
At some point, I'll have to apply an operator of arity n on operands of type Literal *, and I need to get a vector of concrete literals based on the more general (ExpressionLiteral > RealLiteral [...] > IntegerLiteral).
So I tried something like this (example for ExpressionLiteral) :
std::vector<ExpressionLiteral> v;
for (auto op : args) v.push_back(ExpressionLiteral(*op));
where args is std::vector<Literal*>.
This was unsuccessful as ExpressionLiteral has no conversion constructor for Literal.
How can I call the conversion constructor corresponding to the real type of the Literal pointed ?
Thanks for advance.
Aucun commentaire:
Enregistrer un commentaire