C ++ pointer to non-static member functions

I read a lot of posts and answers about pointers to non-static member functions, but no one can solve my problem.
Therefore, I created a short example to replicate my problem here: even if this example can be "solved" in different ways, it is important for the final software to maintain the structure, as in the example, thanks.

This is the title of the "Funcs.h" class:

class Funcs
{
private:
  double a = 1, b = 2;

public:
  Funcs();
  ~Funcs();
  double Fun1(double X);
  double solver(double X0);
  double aaa(double(*fun)(double), double x0);
};

This is the cpp class "Funcs.cpp":

#include "Funcs.h"

using namespace std;

Funcs::Funcs()
{
}

Funcs::~Funcs()
{
}

double Funcs::Fun1(double X) {
  double f1 = a*X;

  return f1;
}

double Funcs::solver(double X0)
{
  double result;

  result = aaa(Fun1, X0);
  return result;
}

double Funcs::aaa(double(*fun)(double), double x0)
{
  return fun(x0);
}

And finally, this is the main "main.cpp":

#include <iostream>
#include "Funcs.h"

using namespace std;

int main() {
  double x0=1;
  double result;
  Funcs funcs;

  result = funcs.solver(x0);
  cout << result << endl;

  return 0;
}

Funcs:: solver, "result = aaa (Fun1, X0)"; Fun1, . , "" .

.

+6
3

, -, -- -. .

"fun" - : double(*fun)(double).

- Funcs: double(Funcs::*fun)(double)

, , .

class Funcs
{
  // all the rest is the same
  double aaa(double(Funcs::*fun)(double), double x0);
};

double Funcs::solver(double X0)
{
  // ...
  result = aaa(&Funcs::Fun1, X0);
  // ...
}

double Funcs::aaa(double(Funcs::*fun)(double), double x0)
{
  return (this->*fun)(x0);
}

Coliru.

, aaa, - Funcs fun. , , , , lambdas aaa, std::function.

+6

, --. this -. , aaa - , , , , aaa, double(Funcs::*)(double), double(*fun)(double). aaa .

+4

Funcs::Fun1 double(*)(double).

​​: return_type(*)(class_type* this, arguments...)

:

//first argument of `aaa` has type double(*)(double)
double aaa(double(*fun)(double), double x0);

double Funcs::Fun1(double X) {
  double f1 = a*X;

  return f1;
}

// Fun1 has type double(Funs::*)(double)
// i.e it a method of Funs and it takes (implicitly) first argument
// which is `this` pointer

// so that how `aaa` must  look like
double aaa(double(Funs::*fun)(double), double x0)
{
    // special sytax
    *this.*fun(x0);
}

// and that how `solver` looks like
double Funcs::solver(double X0)
{
  double result;

  // get pointer to method
  result = aaa(&Funs::Fun1, X0);
  return result;
}

- this

+2

All Articles