C ++ An external function with a function pointer as a parameter used inside a class with a member function

Pretty new to C ++. Suppose I have a class:

class A { private: double m_x, m_y; public: A(double x, double y): m_x {x} { m_y = extF(m_x, y, *intF); } double intF(double x) { return 2*x; } }; 

And it uses an external global function defined elsewhere:

 double extF(double x, double y, std::function<double(double)> f) { if (x*y < 0) return f(x); else return f(y); } 

Formulas are fictitious. This does not compile. I tried simple intF , A::*intF , &A::intF , even some unorthodox combinations, but this is just fortunetelling. The problem is that class A not the only one that uses a global external function, and that is what should be the user's choice at runtime. Searches showed some answers saying that it is impossible to make a pointer to a member function like this because it needs an instance (?), But I did not find solutions. It can be done? If so, how?


Edit: Additional question: how can there be a pointer to a member function if the member function is const double f(...) const ?

+3
source share
2 answers

One option is to just use lambda:

 class A { private: double m_x, m_y; public: A(double x, double y): m_x {x} { m_y = extF(m_x, y, [&](double d){ return intF(d);}); } double intF(double x) { return 2*x; } }; 

Another option is to use lambda and std::mem_fn (excluding the rest of your class code):

 A(double x, double y): m_x {x} { auto fn = std::mem_fn(&A::intF); m_y = extF(m_x, y, [&](double d) {return fn(this, d);}); } 

And finally, you can get rid of lambda if the bind parameter of the member function pointer object is:

 A(double x, double y): m_x {x} { auto fn1 = std::bind(std::mem_fn(&A::intF), this, std::placeholders::_1); m_y = extF(m_x, y, fn1); } 

All of this also works with persistent member functions.

+3
source

You can use std::bind to bind a member function.

 A(double x, double y): m_x {x} { using namespace std::placeholders; m_y = extF(m_x, y, std::bind(&A::intF, this, _1)); } 

Or use lambda .

 A(double x, double y): m_x {x} { m_y = extF(m_x, y, [this](double d) { return intF(d); }); } 

BTW: It also works well with the const member function, which doesn't matter here.

Live

+2
source

All Articles