So I got a c++11 book. I've been following a few of the language differences and features for a while, but I decided to break down and actually understand it all. I decided to have some fun with lambdas today. Lambdas are a very useful language feature that lots of dynamic languages have (JavaScript, Python, <insert your favorite there is plenty>). For some additional readying you might read about Closures and Functors.

Anyway, so here you go:

Basic syntax

  1.  
  2. [...] {...} // simplest form
  3. // or showing all the optional arguments
  4. [...] (...) mutable throwSpec -> retType {...}
  5.  

What does that all mean?

The brackets are a parameter list of values you can pass in for usage in the lambda from the context in which the lambda is being created. You could pass in local variables or this for instance. You can pass by a value or reference. Unlike other languages, if you pass by reference and the value is deleted, your lambda might have unexpected results or crash.

The parenthesis are the parameters you pass in when you call the lambda. Declared like a parameter list for any other function. auto is nice but if you need the type (like to return a lambda from a function) you can use the functional header.

Example:

  1.  
  2. #include <functional>
  3. #include <iostream>
  4. using namespace std;
  5.  
  6. function<int(int,int)> getTheLambda()
  7. {
  8. int x=7;
  9. // will return an undefined value because x is going to be removed from
  10. // the stack when this function exits.
  11. return [&x] (int a, int b) { return x+a+b; };
  12. }
  13.  
  14. int main(int argc, char* argv[])
  15. {
  16.  
  17. auto m = [] (int y) { cout << "lamda value: " << y << endl; };
  18. // call it
  19. m(3);
  20.  
  21. auto l=getTheLambda();
  22. cout << "Lambda Result: " << l(1,2) << endl;
  23.  
  24. return 0;
  25. }
  26.  

For me it printed:

  1.  
  2. ./test
  3. lamda value: 3
  4. Lambda Result: 32770
  5.  

If you change the first lamba in the function to "x" instead of "&x" you'll get the expected result of 10.

I can't wait to pass a lambda to a thread and use it as some type of callback!