Home > Mobile >  Passing a member function pointer to a non-member function within another member function
Passing a member function pointer to a non-member function within another member function

Time:02-03

I have a code similar to the minimal example below, where the function g is provided by a library and expects double (*)(double) as an argument. I cannot change this. The example code does not compile because the member has signature double (*C::)(double) as explained in e.g. this post, with a number of possible solutions.

#include <iostream>

double g(double (*f)(double x)) { return f(0); };

class C
{   
   public:
      C(double b) { a = b; };
      double f2() { return g(&f1); };
   private:
      double a;
      double f1(double x) { return x   a; };
};

int main()
{
   C c (1);
   std::cout << c.f2() << std::endl;
   return 0;
}

I wonder what the best way to implement this is given that I don't want to point to C::f1 outside the class but within another member function. As far as I understand, the member function C::f1 is not static since it is only fully known after an instance of the class is initialised. Since speed is also a concern: would this be a problem with any of the possible solutions proposed elsewhere for similar versions of this issue?

CodePudding user response:

Make your f1 function static:

  static double f1(double x) { return x   a; };

This gives it the same signature as what your g function expects. Since a static function does not have a hidden this pointer, you will have to find some other way to get the value of a into it.

CodePudding user response:

Okay, based on the comments and ideas from the post mentioned before, I will suggest to change g as follows and add a wrapper function f2_wrapper.

#include <iostream>

double g(double (*f)(double x, void *context), void *context)
{
   return f(0, context);
};

class C
{   
    public:
        C(double b) { a = b; };
        double f1(double x) { return x   a; };
        double f2();
    private:
        double a;
};

double f2_wrapper(double x, void* context)
{
    C *c = (C*) context;
    return c->f1(x);
}

double C::f2() { return g(&f2_wrapper, this); }

int main()
{
    C c (1);
    std::cout << c.f2() << std::endl;
    return 0;
}
  •  Tags:  
  • Related