I need to parse a source code. I've identified 3 different types of tokens : symbols (operators, keywords), litterals (integers, strings, etc...) and identifiers.
I already have the following design, with a base class that keeps track of the type of the subclass so it can be downcasted using a base class pointer :
class Token
{
type_e type; // E_SYMBOL, E_LITTERAL, E_TOKEN
};
class Symbol : public Token
{
const symbol_e symbol;
};
class Litteral : public Token
{
const Value value;
};
class Identifier : public Token
{
const std::string name;
};
I need these classes to be stored in a single array of tokens, that's why i need them to have a common base class. Then i use them like this :
if( cur->type == E_SYMBOL && static_cast< const Symbol * >( cur )->symbol == E_LPARENT )
{
// ...
}
I could create virtual functions isSymbol, isLitteral, isIdentifer that each subclass would override, but i would still have to downcast the base class pointer to a subclass pointer so i can access the subclass's specific data.
People say downcasting means the interface is likely flawed, and it's making the syntax very heavy, so i'd like to find another way, but i can't. Some people suggested the visitor pattern, but i'm afraid this would uselessly complexify the code and i don't even understand how i could use the visitor pattern with this problem.
Can anyone help ? Thank you :)