I am writing an Interpreter in c++ as a course work at the uni. Basically i'm translating this python interpreter to c++ by myself using google.
using visitor for an interpreter I have 2 classes
BinOp : public AST
Number : public AST
I have 2 methods in my Interpreter class
class Interpreter : public NodeVisitor
int visitBinOp(BinOp* node)
{
//example if the operation is +
//return this->visit(node->left) + this->visit(node->right)
}
int visitNumber(Number* node)
{
//returns the int value that's in the node.
//return node->value;
}
and 1 method in NodeVisitor that Interpreter inherits
class NodeVisitor
int visit(AST* node)
{
//if node is BinOp properFunction is pointer to visitBinOp
//if node is Number properFunction is pointer tp visitNumber
//return properFunction(node)
}
Question 1:Whats the best way to check if AST is BinOp or Number
if(typeid(node) == typeid(BinOp*)
or through some casting (when trying dynamic_cast I get error that classes arent polymorphic).
Main Problem: I need to somehow to create a pointer to those functions but don't know how to.
EDIT 1 Added this code to NodeVisitor but due to it including "Interpreter.h" and Interpreter including "NodeVisitor.h" i get
error C2504: 'NodeVisitor' : base class undefined.
unsigned long int NodeVisitor::visit(AST* node)
{
std::function<unsigned long int(Number* node)> visitNumber = std::bind(&Interpreter::VisitNumber);
std::function<unsigned long int(BinaryOperation* node)> visitBinOp = std::bind(&Interpreter::VisitBinOp);
if (typeid(node) == typeid(Number*))
{
visitNumber((Number*)node);
}
if (typeid(node) == typeid(BinaryOperation*))
{
visitBinOp((BinaryOperation*)node);
}
}
I think i need to add extern "C" to visitBinOp and visitNumber funcs and use this approach, mentioned in here
void *handle = dlsym(0, RTLD_LOCAL | RTLD_LAZY);
FunctionType *fptr = (FunctionType *)dlsym(handle, "visitBinOp/visitNumber");
fptr();
But im not quite sure how this works.