I wanted to do a recursive evaluation tree for an interpret that returns different types depending on the evaluation in few lines and with no void *
so here is a small example of code of what I was trying to do and didn't work
#include <iostream>
using namespace std;
struct node{
node(string _text){
child = NULL;
sibling = NULL;
text = _text;
}
node *child;
node *sibling;
string text;
};
auto evaluate(node *n){
if(n->text == "sum"){
return (int)evaluate(n->child) + (int)evaluate(n->child->sibling);
}else if(n->text == "lt"){
return (int)evaluate(n->child) < (int)evaluate(n->child->sibling);
}else{
return atoi(n->text.c_str());
}
}
int main(){
node sum = node("sum");
node a_value = node("23");
node b_value = node("13");
sum.child = &a_value;
sum.child->sibling = &b_value;
cout << (int)evaluate(&sum) << endl;
}
I would like to know if there is a simple way to do this using modern c++.
sum.child = &a_value;
remember that the nodes go away when the scope ofa_value
ends.std::any
orstd::variant
?auto
as a return type is allowed only if the compiler can determine the return type at compile time. The compiler does not appreciate being called recursively with anauto
return type. As all return types of evaluate areint
, by specifying the return type explicitly, the code functions. If this is not your intent, then you will need to do this without auto.