简体   繁体   中英

C++ Binding non-static member function

I am trying to pass a member function to another function in a nested class.

Passing a non-member function works well but passing the member does not compile:

Ah:
 class A { class B { B(); ~B(); doSomething(); }; class C { C(); ~C(); execute(function<void(void)> func); }; C *myC; map<int, B> myMap; }
A.cpp:
 void A::member(int param) { A::myMap[param].doSomething(); } void nonA_func(int param) { ... } void A::caller() { myC->execute(bind(nonA_func, 42)); // OK myC->execute(bind(A::member, 42)); // COMPILER ERROR 1 myC->execute(A::myMap[42].doSomething()); // COMPILER ERROR 2 } A::main() { myC = new A::C(); // filling myMap caller(); myMap.clear(); delete C; }

When compiling the following COMPILER ERROR 1 occurs:

 error: invalid use of non-static member function myC->execute(bind(A::member, 42)); ^

Actually defining A::member as static solves this problem, but then I can't access myMap anymore. How can I bind the non-static member function?


I have also tried to pass the called function directly, resulting in COMPILER ERROR 2 :

 invalid use of void expression myC->execute(A::myMap[42].doSomething()); ^

You need to pass the this pointer to bind (or lambda). You can't use instance variables/functions without an instance.

myC->execute(bind(&A::member, this, 42));
myC->execute([this]{ member(42); });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM