C++ lambda’s in a little more depth

Lambda expressions appeared in C++ 11.

Let’s take a simple example. We want to create a lambda which takes an enum (of type UpdateFlag) and returns a LPTSTR (yes we’re in Visual C++ world) which we’ll use when we writing to cout.

We can create the lambda like this

auto lambda = [](UpdateFlag flag)
{
   switch (flag)
   {
      case UpdateFlag::Update:
         return _T("Update");
      case UpdateFlag::Delete:
         return _T("Delete");
      case UpdateFlag::Missing:
         return _T("Missing");
   }
};

if you prefer to not use the auto keyword we can use the functional code like this

std::function<LPCTSTR(UpdateFlag)> lambda = [](UpdateFlag flag)
{
// switch removed for brevity
};

I’m not quite sure where you’d need to use the std::function variation of this, but this is what it would look like.

Now to use our lambda, we’d simply have something like

std::cout << lamba(updateFlag);

We can also pass the lambda (without creating a variable to it) using the following

std::cout << [](UpdateFlag flag)
{
// switch removed for brevity
}(updateFlag);

Note: we need to pass the updateFlag in a parameter list after the lamba declaration.

The [] is an empty capture list, we could alter the previous samples (assuming a variable updateFlag is available within the scope of the lambda) by passing the updateFlag as part of the capture list, for example

auto updateFlag = UpdateFlag::Update;

auto lambda = [updateFlag]
{
   switch (updateFlag)
   {
      case UpdateFlag::Update:
         return _T("Update");
      case UpdateFlag::Delete:
         return _T("Delete");
      case UpdateFlag::Missing:
         return _T("Missing");
   }
};

Structuring the lamba

Let’s look at the format of the lamba…

The lamba syntax basically takes the form

  • [capture-list] (params) mutable(optional) constexpr(optional)(c++17) exception attribute -> ret { body }
  • [capture-list](params) -> ret { body }
  • [capture-list](params) { body }
  • [capture-list] { body }

The above is replicated from the Lambda expressions page.

The capture-list is a comma seperated list of zero or more captures, which takes or “captures” variables to be passed into the lambda.

The params are a standard list of parameters to pass into your lambda and the body is your actual code.

References

An excellent article on the subject of C++ 11 lambda’s can be found here.
The lambda specification can be found here.