-2

Possible Duplicate:
Is there any kind of “expression class” (C++)

I want to make a class that holds a function that is defined at run time. i.e.

function function1("x*sin(3.141*x)");

I want to do things like find roots and it would be better not having to rewrite the program each time.

edit: I am looking at lua.

Community
  • 1
  • 1
user1750289
  • 17
  • 1
  • 7
  • 2
    Do you mean you want to evaluate a string containing a C++ expression? Your question isn't really clear at the moment... – Ry- Nov 09 '12 at 18:29
  • Depending on what you're actually asking, you might be interested in [muParser](http://muparser.beltoforion.de/). – DSM Nov 09 '12 at 18:31
  • Yes I want to take a string from the user and store it in a class and then use it like a math expression. What is unclear so I can correct it? – user1750289 Nov 09 '12 at 18:31
  • Why do you want to use C++ for this? This kind of thing is very simple in dynamic languages, e.g. in Python it's just `eval`. It's by nature much more cumbersome in static languages. – leftaroundabout Nov 09 '12 at 18:33
  • I mean a math function, function1 is an example of how I want to initialize a class named function as it is holding a math function. – user1750289 Nov 09 '12 at 18:34
  • 1
    @fork, C++ has no methods it has member functions. – 111111 Nov 09 '12 at 18:36
  • @leftaroundabout, I want to use c++ as the function will be evaluated alot so I want the speed of a compiled language. – user1750289 Nov 09 '12 at 19:13
  • Well, then you need to compile it, otherwise you obviously _won't_ get this speed. You won't need to _build_ your entire program, just compile the file with your formula in it and link it to the program. – leftaroundabout Nov 09 '12 at 21:37

1 Answers1

0

This thing is certainly much easier in dynamic languages. For example, in Matlab you can evaluate strings using the eval command.

However, this is not impossible in C++. You might be able to make a nice solution with a combination of C++11 lambdas and a custom interpreter. The member function can take a lambda as an argument, and you can formulate the lambda by interpreting a string.

This answer might give you a good starting point for the interpreting part of the challenge.

Evaluate Mathematical Function from String

Community
  • 1
  • 1
learnvst
  • 15,455
  • 16
  • 74
  • 121