Niklas Niklas - 1 year ago 123
C++ Question

c++ pass data source function as parameter

I have a static function:

void E::createEP(std::list<double>* ret, double length, double (*getHeight)(double)) {
// magic
double sampleIntervall = //from magic

double dist = 0;
while (length - dist > -0.1) {
ret->push_back(dist, (*getHeight)(dist));
dist += sampleIntervall;

In different calls I have two different functions to pass as getHeight():

  • A function in a database wrapper class which is not static

  • A function within the same Object of type
    (for "recreating" with different parameters), which needs to access Elements fields and can thus not be static, either.

Is it somehow possible to pass non-static functions as parameters to a static function?

If not, what would be the most elegant alternative? I don't want to duplicate the entire code in

Answer Source

What you can use is a std::function. It will wrap a callable type be that a function, member function, object with an overloaded function operator. You just need to supply the signature to use. So in you case you would have

void E::createEP(std::list<double>* ret, double length, std::function<double(double)> getHeight) 

Then to bind the member function with the object you want to call it on you can use a lambda like

[&](double val){ return object.FunctionName(val); }

or std::bind like

std::bind(&ClassName::FunctionName, &object)
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download