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 const 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
73 printf("Error: %02d Pos: %02d Type: [%14s] Message: %s\tExpression: %s\n",
74 static_cast<unsigned int>(error_idx),
75 static_cast<unsigned int>(error.token.position),
76 exprtk::parser_error::to_str(error.mode).c_str(),
77 error.diagnostic.c_str(),
78 expression_str.c_str());
79 }
80
81 continue;
82 }
83
84 // Modify all the variables from both the immutable
85 // and mutable symbol tables
86
87 x += 1.1;
88 y += 2.2;
89 z += 3.3;
90 w += 4.4;
91
92 expression.value();
93 }
94
95 return;
96}
97
98int main()
99{
100 immutable_symtab_example<double>();
101 return 0;
102}
103
104
std::string to_str(error_mode mode)
Definition exprtk.hpp:22363