Storing function pointers
The following uses a simple function pointer, but what if I want to store that function pointer? In that case, what would the variable declaration look like?
#include <iostream>
#include <vector>
using namespace std;
double operation(double (*functocall)(double), double wsum);
double get_unipolar(double);
double get_bipolar(double);
int main()
{
double k = operation(get_bipolar, 2); // how to store get_bipolar?
cout << k;
return 0;
}
double operation(double (*functocall)(double), double wsum)
{
double g = (*functocall)(wsum);
return g;
}
double get_unipolar(double wsum)
{
double threshold = 3;
if (wsum > threshold)
return threshold;
else
return threshold;
}
double get_bipolar(double wsum)
{
double threshold = 4;
if (wsum > threshold)
return threshold;
else
开发者_开发百科 return threshold;
}
You code is almost done already, you just seem to call it improperly, it should be simply
double operation(double (*functocall)(double), double wsum)
{
double g;
g = functocall(wsum);
return g;
}
If you want to have a variable, it's declared in the same way
double (*functocall2)(double) = get_bipolar;
or when already declared
functocall2 = get_bipolar;
gives you a variable called functocall2
which is referencing get_bipolar, calling it by simply doing
functocall2(mydouble);
or passing it to operation by
operation(functocall2, wsum);
You already (almost) have it in your code:
double (*functocall)(double) = &get_bipolar;
This defines a function pointer named functocall
which points to get_bipolar
.
typedef double (*func_t)(double);
func_t to_be_used = get_bipolar
typedef double (*PtrFunc)(double);
PtrFunc ptrBipolar = get_bipolar;
OR
typedef double (Func)(double);
Func *ptrBipolar = get_bipolar;
which ever you are comfortable to use.
Have a look at boost function, it's a header only library that tidies things up a little (IMHO): http://www.boost.org/doc/libs/1_42_0/doc/html/function.html
typedef boost::function<double (double)> func_t;
func_t to_be_used = &get_bipolar;
(NB: different syntax required for VC6)
double (*foo)(double);
where foo
is the variable name.
You should consider using a typedef:
typedef double (*MyFunc)(double);
MyFunc ptr_func = &get_bipolar;
(*ptr_func)(0.0);
double operation(MyFunc functocall, double wsum)
{
double g;
g = (*functocall)(wsum);
return g;
}
May I recommend also the identity template trick:
template<class T>
class Id
{
typedef T type;
};
Id<double(double)>::type * ptr_func = &get_bipolar;
MyFunc func = &get_bipolar;
(*ptr_func)(0.0);
double operation(Id<double(double)>::type * functocall, double wsum)
{
double g;
g = (*functocall)(wsum);
return g;
}
精彩评论