Reputation: 1066
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:
A.h: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()); ^
Upvotes: 3
Views: 6339
Reputation: 16421
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); });
Upvotes: 9