Dynamically creating a pointer function in C ++

Today I worked on my modern homework on calculus, and we are doing several Newton method iteration methods to find solutions to things like x ^ 2 = 2. It made me think that I could write a function that takes two pointers to functions: one for the function itself and one for the derivative and automate the process. It would not be too complicated, then I started thinking if I can enter a user function and analyze this input (yes, I can do it). But can I then dynamically create a pointer to a function with a single variable in C ++. For example, if x ^ 2 + x, I can make the function double function (double x) {return x * x + x;} at runtime. Is this remotely possible, or is it consistent with the lines of self-modifying code?

Edit:

So, I suppose how this can be done if you saved the information in an array and it had a function that evaluated the information stored in this array with the given input. Then you can create a class and initialize the array inside that class, and then use the function from there. Is there a better way?

+4
source share
6 answers

You cannot dynamically create a function in the sense that you can generate source machine code for it, but you can easily create mathematical expressions using polymorphism:

struct Expr { virtual double eval(double x) = 0; }; struct Sum : Expr { Sum(Expr* a, Expr* b):a(a), b(b) {} virtual double eval(double x) {return a->eval(x) + b->eval(x);} private: Expr *a, *b; }; struct Product : Expr { Product(Expr* a, Expr* b):a(a), b(b) {} virtual double eval(double x) {return a->eval(x) * b->eval(x);} private: Expr *a, *b; }; struct VarX : Expr { virtual double eval(double x) {return x;} }; struct Constant : Expr { Constant(double c):c(c) {} virtual double eval(double x) {return c;} private: double c; }; 

You can then Expr your expression in the Expr object at runtime. For example, x^2+x would be Expr* e = new Sum(new Product(new VarX(), new VarX()), new VarX()) . Then you can evaluate this for a given value of x with e->eval(x) .

Note: in the code above, I ignored const-correctness for clarity - you shouldn't :)

+3
source

As others have said, you cannot create new C ++ functions at run time in any portable way. However, you can create an expression evaluator that can evaluate things like:

  (1 + 2) * 3 

contained in the string at runtime. It is easy to expand such an evaluator to have variables and functions.

+4
source

This is the line of self-modifying code, and it is possible, just not in "pure" C ++. You need to know some assemblies and a few implementation details. Without stopping at this path, you can abstractly represent operations (for example, using functors) and build an expression tree that needs to be evaluated.

However, for a simple situation with only one variable that you specified, you will need to store the coefficients, and you can easily evaluate them for a given value.

 // store coefficients as vector in "reverse" order, eg 1x^2 - 2x + 3 // is stored as [3, -2, 1] typedef double Num; typedef vector<double> Coeffs; Num eval(Coeffs c, Num x) { assert(c.size()); // must not be empty Num result = 0; Num factor = 1; for (Coeffs::const_iterator i = c.begin(); i != c.end(); ++i) { result += *i * factor; factor *= x; } return result; } int main() { Coeffs c; // x^2 + x + 0 c.push_back(0); c.push_back(1); c.push_back(1); cout << eval(c, 0) << '\n'; cout << eval(c, 1) << '\n'; cout << eval(c, 2) << '\n'; } 
+3
source

For this, you do not need a code for self-modification. But you will write what comes down to the parser and the interpreter of the expressions. You write code to analyze your function into suitable data structures (e.g. trees). For this input, you now go through the tree and calculate the result of the function. Calculation can be performed through the visitor.

+1
source

You do not need to know the assembly. Write C ++ code for possible expressions, and then write a compiler that examines the expression and selects the appropriate code fragments. This can be done at runtime, as the interpreter usually does, or it can be a compilation step that creates the code to execute by copying the instructions from each evaluation of the expression into the allocated memory and then setting it as a function. The latter is harder to understand and code, but will work better. But for development time and runtime to be less than the interpreted implementation, the compiled code must be used many times (billions) times.

+1
source

As others said. Writing self-modifying code is not required at all and is painful in a compiled language if you want it to be portable. The hardest part of your work is input parsing. I recommend muParser for evaluating your expressions. This should take a lot of pain and you can focus on an important part of your project.

0
source

Source: https://habr.com/ru/post/1305986/


All Articles