0

as little follow up to this: C++ lambda function without C++0x?

I have created the lambda function as a function object without c0x

the question now is:

  • how to pass it as a callback/function pointer to another function?

My first try was like this, but it didn't work:

Lambda Obj( C, D);
command ( Obj.operator()(typeA A, typeB B));

I marked the other question to early i guess, so noone looked at the edit.

Community
  • 1
  • 1
joey
  • 21
  • 3

2 Answers2

2

If you cannot find std::function in std::tr1::function or via std::function or via a compiler upgrade...

Write your own std::function-like type eraser, or use boost, or use 'the fastest possible delegates' (that should google to a complete implememtation), or pass both a this pointer and a method pointer as template-type-deduced arguments to a function, or pass a template-type-deduced copy of the function object to the function.

Note that the last two options require the function's body to be exposed (such as in a header file).

Or convert the function object into a void* style C callback.

I would go with C++11, and failing that boost, and failing that fast delegates, failing that write a type eraser myself, failing that stick body in header and template+pass a copy (unless function is simple, in which case do this first), and failing that pvoid C style.

Yakk - Adam Nevraumont
  • 262,606
  • 27
  • 330
  • 524
1

Using Boost.Bind:

void command(boost::function<void()> func)
{
    func();
}

Lambda Obj(C, D);
command(boost::bind<void>(Obj, A, B));

(or maybe you wanted to have):

void command(boost::function<retType(typeA, typeB)> func)
{
    retType ret = func(A, B);
}

Lambda Obj(C, D);
command(boost::bind<retType>(Obj, _1, _2)); // placeholders

Using templates (the STL's way):

template <typename F>
void command(F func)
{
    func(A, B);
}

Lambda Obj(C, D);
command(Obj);

Live demo link.

Piotr Skotnicki
  • 46,953
  • 7
  • 118
  • 160