C++ Mathematical Expression Toolkit (ExprTk) release
Loading...
Searching...
No Matches
exprtk_immutable_symbol_table_example.cpp
Go to the documentation of this file.
1/*
2 **************************************************************
3 * C++ Mathematical Expression Toolkit Library *
4 * *
5 * ExprTk Immutable Symbol Table Example *
6 * Author: Arash Partow (1999-2024) *
7 * URL: https://www.partow.net/programming/exprtk/index.html *
8 * *
9 * Copyright notice: *
10 * Free use of the Mathematical Expression Toolkit Library is *
11 * permitted under the guidelines and in accordance with the *
12 * most current version of the MIT License. *
13 * https://www.opensource.org/licenses/MIT *
14 * SPDX-License-Identifier: MIT *
15 * *
16 **************************************************************
17*/
18
19
20#include <cstdio>
21#include <string>
22#include <utility>
23#include <algorithm>
24#include <vector>
25
26#include "exprtk.hpp"
27
28
29template <typename T>
31{
32 typedef exprtk::symbol_table<T> symbol_table_t;
33 typedef exprtk::expression<T> expression_t;
34 typedef exprtk::parser<T> parser_t;
35
36 T x = 1.1;
37 T y = 2.2;
38 T z = 3.3;
39 T w = 4.4;
40
41 symbol_table_t mutable_symbol_table;
42 symbol_table_t immutable_symbol_table(symbol_table_t::symtab_mutability_type::e_immutable);
43
44 mutable_symbol_table.add_variable("x", x);
45 mutable_symbol_table.add_variable("y", y);
46
47 immutable_symbol_table.add_variable("z", z);
48 immutable_symbol_table.add_variable("w", w);
49
50 expression_t expression;
51 expression.register_symbol_table(immutable_symbol_table);
52 expression.register_symbol_table(mutable_symbol_table );
53
54 parser_t parser;
55
56 std::vector<std::string> expressions =
57 {
58 "x := y + (z / w)", // ok - will compile
59 "y := y / x + (z / w)", // ok - will compile
60 "z := y + x - w", // Error - will not compile
61 "z == (w := y / x)", // Error - will not compile
62 };
63
64 for (const auto& expression_str : expressions)
65 {
66
67 if (!parser.compile(expression_str, expression))
68 {
69 for (std::size_t error_idx = 0; error_idx < parser.error_count(); ++error_idx)
70 {
71 const auto error = parser.get_error(error_idx);
72 printf("Error: %02d Pos: %02d Type: [%14s] Message: %s\tExpression: %s\n",
73 static_cast<unsigned int>(error_idx),
74 static_cast<unsigned int>(error.token.position),
75 exprtk::parser_error::to_str(error.mode).c_str(),
76 error.diagnostic.c_str(),
77 expression_str.c_str());
78 }
79
80 continue;
81 }
82
83 // Modify all the variables from both the immutable
84 // and mutable symbol tables
85
86 x += 1.1;
87 y += 2.2;
88 z += 3.3;
89 w += 4.4;
90
91 expression.value();
92 }
93
94 return;
95}
96
97int main()
98{
99 immutable_symtab_example<double>();
100 return 0;
101}
102
103
std::string to_str(error_mode mode)
Definition exprtk.hpp:22098