Misunderstanding a function pointer - passing it as an argument

I want to pass a member function of class A to class B using the function pointer as an argument. Please let me know if this road leads somewhere and helps me fill the pothole.

#include <iostream> using namespace std; class A{ public: int dosomeA(int x){ cout<< "doing some A to "<<x <<endl; return(0); } }; class B{ public: B(int (*ptr)(int)){ptr(0);}; }; int main() { A a; int (*APtr)(int)=&A::dosomeA; B b(APtr); return 0; } 

This brilliant piece of code leaves me with a compiler error:

cannot convert int (A::*)(int)' to int (*) (int)' into initialization

First, I want it to compile.
Secondly, I do not want dosomeA to be STATIC.

+4
source share
2 answers

Pointers to elements differ from ordinary function pointers. Since a compiler error indicates that the type &A::dosomeA is actually int (A::*)(int) , not int (*)(int) .

Inside constructor B you will need an instance of A to call a member when using one of the operators .* Or ->* .

eg

 B(int(A::*ptr)(int)) { A atmp; (atmp.*ptr)(int); } 
+6
source

http://www.parashift.com/c++-faq-lite/pointers-to-members.html

You do not have a pointer to a function that returns int and accepts int. You have a pointer to a member function that returns int and accepts A * and int. Not only do you need to correct the type of your pointer, B must provide A * for the dosomeA this parameter.

Boost :: bind has some functionality designed to simplify the use of function pointers in general, and they provide support for member function pointers. See here .

+3
source

Source: https://habr.com/ru/post/1304549/


All Articles