function pointers

closed account (1b7S216C)
Hi,

I already know how to create functions that return pointers to functions that have already been defined at compile time, like in this example:

1
2
3
4
5
6
7
8
9
10
typedef float(*pt2Func)(float, float); 

float Plus  (float a, float b) { return a+b; } 
float Minus (float a, float b) { return a-b; } 

pt2Func GetPtr2(const char opCode) 
{ 
  if (opCode == ’+’) return &Plus; 
  else               return &Minus;
} 


Now consider the following:

1
2
typedef float(*pt2Func1)(float); 
typedef float(*pt2Func2)(float, float); 


I would like to define a function with prototype

pt2Func1 myfunc(float a, pt2Func2 func_a);

that returns a pointer to the function which, taking another float float b as an argument, returns func_a(a,b).
Is this possible, and if yes, how?

Thanks in advance.

Last edited on
Consider reading up mem_fun and bind in the standard library. Both will be in the reference section of this website.

Additionally, you might want to check out Boost.Member Function, Boost.Bind, and Boost.Function Types.
returns myfunc(a,b).

Which myfunc do you mean? The same as above? Because it doesn't take two floats as its parameters.
If you mean some other function, functors are probably what you're looking for.
closed account (1b7S216C)
Which myfunc do you mean? The same as above? Because it doesn't take two floats as its parameters.
If you mean some other function, functors are probably what you're looking for.


oops, a typo. func_a equals myfunc, of course.
Let's see an example of what the guys above suggested...

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
43
44
45
46
47
48
49
50
#include <iostream>
using namespace std;

typedef float (*fptr)(float,float);

class Function
{
private:

    float a;
    fptr f;

public:

    Function(float a_, fptr f_):
        a(a_),f(f_){}

    float operator()(float b)
    {
        return f(a,b);
    }

};

float myfunc1(float a, float b)
{
    return (a+b)/2.0f;
}

float myfunc2(float a, float b)
{
    return (a-b)/2.0f;
}

int main()
{
    Function f1(3.0f,myfunc1);

    //same as cout << myfunc1(3.0f, 4.0f) << endl;
    cout << f1(4.0f) << endl;

    Function f2(5.0f,myfunc2);

    //same as cout << myfunc2(5.0f, 2.0f) << endl;
    cout << f2(2.0f) << endl;

    cout << "hit enter to quit...";
    cin.get();
    return 0;
}

Is this what you're looking for?
closed account (1b7S216C)
yes, that looks good, thanks!
Isn't that the same as

1
2
3
4
float functionA (float a, float b,   float (*pf)(float, float) )
{
     return  (*pf) (a,b);
}



Edit:
but in my mind the functor does nothing other than store the first parameter and function pointer - so I can't see any great purpose there.
Last edited on
Topic archived. No new replies allowed.