Something went wrong. Try again.
A Tour of C++ for experienced programmers, as if C++26 is the only version that ever existed.
Something went wrong. Try again.
1234567891011121314151617181920212223242526272829303132333435#include <variant>#include <memory>#include <iostream>
struct Node;struct Number { double value; };struct BinaryOp { char op; std::unique_ptr<Node> left; std::unique_ptr<Node> right;};struct Node { std::variant<Number, BinaryOp> expr; double eval() const { struct Visitor { double operator()(const Number& n) const { return n.value; } double operator()(const BinaryOp& b) const { double l = b.left->eval(); double r = b.right->eval(); return b.op == '+' ? l + r : 0.0; } }; return std::visit(Visitor{}, expr); }};
int main() { // Build (1 + 2) + 3 = 6 auto leaf1 = std::make_unique<Node>(Node{Number{1}}); auto leaf2 = std::make_unique<Node>(Node{Number{2}}); auto inner = std::make_unique<Node>(Node{BinaryOp{'+', std::move(leaf1), std::move(leaf2)}}); auto root = std::make_unique<Node>(Node{BinaryOp{'+', std::move(inner), std::make_unique<Node>(Node{Number{3}})}}); std::println("result: {}", root->eval());}