|
| 1 | +// Copyright (c) 2018-2025 Jean-Louis Leroy |
| 2 | +// Distributed under the Boost Software License, Version 1.0. |
| 3 | +// See accompanying file LICENSE_1_0.txt |
| 4 | +// or copy at http://www.boost.org/LICENSE_1_0.txt) |
| 5 | + |
| 6 | +#include <iostream> |
| 7 | + |
| 8 | +// tag::content[] |
| 9 | +struct Node { |
| 10 | + virtual int value() const = 0; |
| 11 | +}; |
| 12 | + |
| 13 | +struct Variable : Node { |
| 14 | + Variable(int value) : v(value) {} |
| 15 | + int value() const override { return v; } |
| 16 | + int v; |
| 17 | +}; |
| 18 | + |
| 19 | +struct Plus : Node { |
| 20 | + Plus(const Node& left, const Node& right) : left(left), right(right) {} |
| 21 | + int value() const override { return left.value() + right.value(); } |
| 22 | + const Node& left; const Node& right; |
| 23 | +}; |
| 24 | + |
| 25 | +struct Times : Node { |
| 26 | + Times(const Node& left, const Node& right) : left(left), right(right) {} |
| 27 | + int value() const override { return left.value() * right.value(); } |
| 28 | + const Node& left; const Node& right; |
| 29 | +}; |
| 30 | + |
| 31 | +// tag::content[] |
| 32 | +#include <boost/openmethod.hpp> |
| 33 | +#include <boost/openmethod/initialize.hpp> |
| 34 | + |
| 35 | +using boost::openmethod::virtual_; |
| 36 | + |
| 37 | +BOOST_OPENMETHOD(postfix, (virtual_<const Node&> node, std::ostream& os), void); |
| 38 | + |
| 39 | +BOOST_OPENMETHOD_OVERRIDE( |
| 40 | + postfix, (const Variable& var, std::ostream& os), void) { |
| 41 | + os << var.v; |
| 42 | +} |
| 43 | + |
| 44 | +BOOST_OPENMETHOD_OVERRIDE( |
| 45 | + postfix, (const Plus& plus, std::ostream& os), void) { |
| 46 | + postfix(plus.left, os); |
| 47 | + os << ' '; |
| 48 | + postfix(plus.right, os); |
| 49 | + os << " +"; |
| 50 | +} |
| 51 | + |
| 52 | +BOOST_OPENMETHOD_OVERRIDE( |
| 53 | + postfix, (const Times& times, std::ostream& os), void) { |
| 54 | + postfix(times.left, os); |
| 55 | + os << ' '; |
| 56 | + postfix(times.right, os); |
| 57 | + os << " *"; |
| 58 | +} |
| 59 | + |
| 60 | +BOOST_OPENMETHOD_CLASSES(Node, Variable, Plus, Times); |
| 61 | + |
| 62 | +auto main() -> int { |
| 63 | + boost::openmethod::initialize(); |
| 64 | + Variable a{2}, b{3}, c{4}; |
| 65 | + Plus d{a, b}; |
| 66 | + Times e{d, c}; |
| 67 | + postfix(e, std::cout); |
| 68 | + std::cout << " = " << e.value() << "\n"; // 2 3 + 4 * = 20 |
| 69 | +} |
| 70 | +// end::content[] |
0 commit comments