Lambdas aren’t just for managed code

A long time ago, I was a C++ developer. I actually thought of myself as a pretty darn good C++ developer and got way too excited when I finally got to meet folks like Scott Meyers and actually landed a job working with Bobby Schmidt-same team on MSDN. (If you know Bobby’s name, well, you were pretty deep into C++ circa 1999.) Then, like many C++ devs, I moved over to a garbage collected language. I’ve done more than my fair share of professional .NET and Java development. C++ has been left by the wayside. Today, I finally downloaded and installed Visual Studio 2010 Beta 2. I dug into the “What’s New” and, out of curiosity, decided to look at C++ first (I already know about many of the C# and VB changes). I saw two cool things:

1. C++ now has an auto keyword. For you C# devs, it is pretty much the same as the C# var keyword.

2. C++ has lambdas.

Now, I’m only a little ways into understanding C++ lambdas, so some of my information here may be suspect. The C++ lambda is just an anonymous function. You can pass variables into the function so that the variable is visible within the function. The syntax is:

[ list of variables from current scope to pass into lambda scope ] return-type( function signature ) { code }

The canonical example appears to be std::for_each from <algorithm>.

#include "stdafx.h"
#include <iostream>
#include <algorithm>
#include <vector>
using namespace std;

int _tmain(int argc, _TCHAR* argv[])
    vector<int> myints;
    for (auto i = 0; i < 10; ++i){
    auto number = 0;
    auto numSquared = 0;
    for_each(myints.begin(), myints.end(), [&number, &numSquared](int n) { 
        cout << n << endl;
        number += n;
        numSquared += n * n;
    cout << "The sum is " << number << endl;
    cout << "The sum of the squares is " << numSquared << endl;
    return 0;

In this example, I have two values: number and numSquared. I make references of the value visible to the lambda, which prints out each value as it comes through and then sums the numbers and their squares. Once the function completes, the code emits the values to the console window. If you don’t want to pass anything to the lambda, you still need to state this. If I didn’t want number or numSquared visible, the lambda signature would be:

[](int n){}

At some point, I’ll dig in and see what else this is good for, including how to build my own Functor signatures. Anyhow, just thought I’d share this little nugget with you.

%d bloggers like this: