Ask about Functional Pointer

Hi everybody ! Anybody helps me plz !
I have problem with functional pointer. I want to calculate single expression with function name was got from keyboard.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
#include <iostream>
#include <string>

using namespace std;

int Add(int a, int b)
{
	return a+b;
}

int Sub(int a, int b)
{
	return a-b;
}

int Cal(int a, int b, int(*g)(int, int))
{
	return g(a, b);
}

int main()
{
	string s;
	cin>>s;
	cout<<Cal(3, 5, Add)<<endl;//It's ok
	cout<<Cal(3, 5, s)<<endl;//But Error
	return 0;
}

How can convert string s to functional Pointer ? Please help help
You will need to create a mapping between words and functions.
Can you clearly explain ?
You cannot directly send a string to your function even if the sting contains the name. You need to take the value of the string, compare the name in some if statement, then send the correct pointer.

1
2
3
4
5
6
7
int (*func)(int, int);
if (str == "Add")
   func = Add;
// more code

//some code later
Cal(3, 5, func);
And if you want to show off to your teacher, consider this STL friendly approach:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
#include <iostream>
#include <string>
#include <map>
using namespace std;

typedef int(*Function)(int,int);
typedef map<string,Function> Dispatcher;

int Add(int a, int b) { return a+b; }
int Sub(int a, int b) { return a-b; }
int Mul(int a, int b) {	return a*b; }

int Cal(int a, int b, const string & f, const Dispatcher & d)
{
    Dispatcher::const_iterator it;
    it=d.find(f);

    if (it==d.end())
    {
        cout << "function not found..." << endl;
        return 0;
    }

    return it->second(a,b);
}

int main()
{
    Dispatcher d;

    d["add"]=Add;
    d["sub"]=Sub;
    d["mul"]=Mul;

    cout << Cal(3,2,"add",d) << endl;
    cout << Cal(3,2,"sub",d) << endl;
    cout << Cal(3,2,"mul",d) << endl;
    cout << Cal(3,2,"asdf",d) << endl;

    cin.get();
    return 0;
}

And if you want to show off to your teacher, consider this STL friendly approach:


This will either impress your teacher, or cause him to slap you for obviously using somebody else's code instead of coming up with your own solution =P I predict the latter.
Last edited on
No. Not my purpose. If do like that, I can use if or case statement, no need Dispatcher. I want the function name (add, sub, mul...) is string, which get from keyboard.
Topic archived. No new replies allowed.