[Cs3] lambdas and function pointers

Mikhail Nesterenko mikhail at cs.kent.edu
Tue Oct 4 11:31:23 EDT 2016


CS3 students,

This is regrading yesterday's discussion on taking lambda's out of
defining scope. The standard is that a non-capturing lambda may be
assigned to a function pointer. That is:

// this is valid
int (*f)(int) = [](int i){return i+5;}; // note the empty capture block

Then, this function pointer may be passed to another function as a
parameter, stored in an array, etc. For example:

void func(int(*param)(int)){
     cout << param(55) << endl;
}

The invocation of this function with the above function pointer would
be:

	func(f);

I put this together as an example here:
   http://vega.cs.kent.edu/~mikhail/classes/cs3/Examples/STLAlgorithms/Functors/fpLambda.cpp

However, capturing lambdas cannot be assigned to function pointers
since they are accessing context variables. A replacement construct is
std::function (to be studied later). Here is an example:

  http://vega.cs.kent.edu/~mikhail/classes/cs3/Examples/STLAlgorithms/Functors/function.cpp

Thanks,
-- 
Mikhail


More information about the cs3 mailing list