7

I've written a function foreach that accepts a lambda function ala:

void foreach(void (*p)(pNode))
{ /* ... */ }

Which works as intended if I pass a 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 within 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 inside the member method of class Object 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 realize this is the compiler being safe, since I could include instance-specific variables inside the lambda function, in which case the lambda would need to be scoped, however I'm wondering if it's possible to make this lambda "static".

I've tried a reinterpret_cast, however that gives me this error:

error: invalid cast from type ‘Object::method()::<lambda(pNode)>’ to type ‘void (*)(pNode)’

Specifying static before [&](pNode ... doesn't seem like valid syntax either.

Desperately, I also tried changing [&] to [=], [], [a], none of which worked.

Does anyone know if there is a way to do accomplish my goal of creating a "static" lambda function, or at any sort of lambda function that will be accepted for that matter?

Thanks!


Answer:

With help from Cat Plus Plus, I was able to turn my incorrect code:

void foreach(void (*p)(pT))
{
    for(pTiter i = _map.begin(); i != _map.end(); i++)
    {
        (*p)(i->second);
    }
}

into fully functional code:

void foreach(std::function<void(pT)>(p))
{
    for(pTiter i = _map.begin(); i != _map.end(); i++)
    {
        p(i->second);
    }
}

that does what I was looking for perfectly.

Community
  • 1
  • 1
jedwards
  • 29,432
  • 3
  • 65
  • 92

1 Answers1

8

Well, you can not use pointers.

void foreach(std::function<void(pNode)>);
Cat Plus Plus
  • 125,936
  • 27
  • 200
  • 224
  • Thank you -- I'll edit my original question to reflect my final (now working!) code. – jedwards Jun 13 '11 at 22:59
  • 3
    Note that according to the FDIS a captureless lambda is implicitly convertible to a function pointer. I.e., the OP's code should have been fine for a captureless (`[]`) lambda. – ildjarn Jun 13 '11 at 23:12
  • Well the `[]` lambda didn't work but for another reason that I wasn't really clear about, I needed to use the arguments that were passed to the member method (not member variables) inside the lambda function. The actual call was closer to `o.method(2,5){/*...*/}`. Thanks for the note about where it would have worked. – jedwards Jun 13 '11 at 23:32