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'; }
Roger Pate
source share