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?