c++ - ExprTk:当表达式的值改变时是否必须重新编译表达式

标签 c++ exprtk

我正在用 exprtk 创建一个表达式使用不断变化的变量。

每次更改变量值时,我是否必须使用更新的 exprtk::symbol_table 重置和重新编译 exprtk::expression

或者更新后的值是否直接由现有的编译表达式求值?

#include <iostream> 
#include <string>
#include "exprtk.hpp"

int main() {
    std::string expression_string = "y := x + 1";

    int x = 1;

    exprtk::symbol_table<int> symbol_table;
    symbol_table.add_variable("x", x);

    exprtk::expression<int> expression;
    expression.register_symbol_table(symbol_table);

    exprtk::parser<int> parser;

    if (!parser.compile(expression_string, expression))
    {
        std::cout << "Compilation error." << std::endl;
        return 1;
    }

    expression.value(); // 1 + 1

    x = 2;
    // Do I have to create a new symbol_table, expression and parse again?

    // Or does the expression evaluate the new value directly?
    expression.value(); // 2 + 1?

    return 0;
}

最佳答案

exprtk::symbol_table 引用的变量值发生变化时,

exprtk::expression 不必 重新编译。 expression.value() 可以立即使用。

According to the documentation (第 10 节 - 组件),符号表中引用的变量的实际值在表达式被计算之前才被解析。所以用解析器编译相同的表达式必须只发生一次。

std::string expression_string = "x * y + 3";
symbol_table.add_variable("x",x);
symbol_table.add_variable("y",y);

expression.register_symbol_table(symbol_table);

parser.compile(expression_string,expression);

x = 1.0;
y = 2.0;
expression.value(); // 1 * 2 + 3

x = 3.7;
expression.value(); // 3.7 * 2 + 3

y = -9.0;
expression.value(); // 3.7 * -9 + 3

// 'x * -9 + 3' for x in range of [0,100) in steps of 0.0001
for (x = 0.0; x < 100.0; x += 0.0001)
{
    expression.value(); // x * -9 + 3
}

During the compilation process [..] the element will be embedded within the expression's AST. This allows for the original element to be modified independently of the expression instance [...] the variables are modified as they normally would in a program, and when the expression is evaluated the current values assigned to the variables will be used.

关于c++ - ExprTk:当表达式的值改变时是否必须重新编译表达式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43312247/

相关文章:

c++ - 在 Cmake 中将 flto=jobserver 传递给 gcc

c++ - 简单的字符串比较如何导致 OleException?

c++ - 无法推断 'TYPE' 的模板参数

c++ - 在这里删除 c++ volatile 是否安全?

c++ - Qt Creator 在新项目中显示错误,但代码编译正常

C++ 和 ExprTk 解析器 "use of deleted function"错误

c++ - exprtk 中的变量区分大小写吗?

c++ - ExprTK 未知变量解析取决于表达式类型

c++ - Exprtk 解析器无法在 VS 2015 上运行?