Input-defined function

I'm creating a program that is going to need a function to be defined for each object.

I.e: an object representing a line
1
2
3
4
struct line
{
   bool f(pair<float,float> pt);
}


Where f returns true if the coordinates of pt are a part of the line while the object represents. However, the object is created via user input, so the exact contents of f are not known a priori. Is it possible to have the user type "1+2*x" and have that equation be saved in f?

I mean, I've thought of this code
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
class line
{
   float a,b;
   public:
   bool f(pair<float,float> pt);
   void create_f(string str);
}
void line::create_f(string str)
{
   size_t pos = str.find("+");
   str _a = str.substr(0,pos);
   a = atoi(_a.c_str());
   size_t pos2 = str.find("*");
   str _b = str.substr(pos+1,pos2);
   b = atoi(_b.c_str());
}
bool line::f(pair<float,float> pt);
{
   if(pt.second == a + b*pt.first)
      return true;
   return false;
}


Mind you, I haven't actually tested this code, I just wrote it down here, so it might (probably) be wrong. Also, it's very simplistic (expects "a+b*x", not "b*x+a"; expects only "+b", not "-b"; etc), but it's simply to make a point.

I just want to know, is there an easier way of doing this?
Last edited on
Not really, you are going to have to parse the data yourself at some point. I think the easiest way of doing this would to be just get the numbers individually.

Btw, about line 19...this line will probably never be true unless you are lucky:
http://docs.sun.com/source/806-3568/ncg_goldberg.html
Oh, I know. This example is actually absurdly simplified. Hell, the actual question is how to select a displayed line with a mouse click. I haven't found any library that deals with such things (any suggestions are more than welcome), so I've started thinking of how to do it myself.

So the real program would generate the line on screen and save the function that represents it ("y=2+3*x"). Then, on each mouse-click, it would throw the values of the coordinates of the click into f(). Obviously, due to the inaccurate nature of not only floating-point arithmetic but of mouse clicks, the program would need to have a tolerance programmed into it.

The fun part will be once I start making regions. Then the click will need to be checked against each function representing each border. This program is not going to be good for large models. I'm sure there's a better method, but I simply don't even know what to start looking for.
Topic archived. No new replies allowed.