I wrote a foreach function that accepts the ala lambda function:
void foreach(void (*p)(pNode)) { }
How it works if I pass the lambda function from the main loop:
int a = 5; env.N().foreach ( [&](pNode n)->void { n->tps(a); } );
However, if I try to call the same function from a member method, the lambda function "inherits" the scope of the member function and generates a compiler error. For example, if I try to include it in a member method of the Object class named method() , I get the following error:
error: no matching function for call to 'IDSet<Node>::foreach(Object::method()::<lambda(pNode)>)' note: candidate is: void IDSet<T>::foreach(void (*)(IDSet<T>::pT)) [with T = Node, IDSet<T>::pT = pNode]
I understand that this compiler is safe, since I could include instance-specific variables inside a lambda function, in which case the lambda should be limited, however I am wondering if it is possible to make this lambda βstaticβ. "
I tried reinterpret_cast , however this gives me this error:
error: invalid cast from type 'Object::method()::<lambda(pNode)>' to type 'void (*)(pNode)'
Setting static to [&](pNode ... also doesn't seem to be valid syntax.
Desperately I also tried to change [&] to [=] , [] , [a] , none of which worked.
Does anyone know if there is a way to make my goal of creating a βstaticβ lambda function or any lambda function to be adopted in this regard?
Thanks!
Answer:
With Cat Plus Plus, I was able to rotate my wrong code:
void foreach(void (*p)(pT)) { for(pTiter i = _map.begin(); i != _map.end(); i++) { (*p)(i->second); } }
into a fully functional code:
void foreach(std::function<void(pT)>(p)) { for(pTiter i = _map.begin(); i != _map.end(); i++) { p(i->second); } }
which does what I was looking for perfectly.