Dr. Dobb's is part of the Informa Tech Division of Informa PLC

This site is operated by a business or businesses owned by Informa PLC and all copyright resides with them. Informa PLC's registered office is 5 Howick Place, London SW1P 1WG. Registered in England and Wales. Number 8860726.

Channels ▼


Efficient Use of Lambda Expressions and std::function

Functor classes — classes that implement operator() — are old friends to C++ programmers who, for many years, have used them as predicates for STL algorithms. Nevertheless, implementing simple functor classes is quite cumbersome as the following example shows.

Suppose that v is an STL container of ints and we want to compute how many of its elements are multiple of a certain value n set at runtime. An STL way of doing this is:

std::count_if(v.begin(), v.end(), is_multiple_of(n));

where is_multiple_of is defined by:

class is_multiple_of {
  typedef bool result_type;  	// These two typedefs are recommended but not
  typedef int argument_type; 	// strictly required. More details to come.
  is_multiple_of(int n) : n(n) {}
  bool operator()(int i) const { return i%n == 0; }
  const int n;

Having to write all this code pushes many programmers to write their own loops instead of calling std::count_if. By doing this, they lose good opportunities for compiler optimizations.

Lambda expressions make creation of simple functor classes much easier. Although two of the Boost libraries — Boost.Lambda and, more recently, Boost.Phoenix — provide very good implementations of lambda abstractions in C++03, to improve the language expressiveness, the standard committee decided to add language support for lambda expressions in C++11. Using this new feature, the previous example becomes:

std::count_if(v.begin(), v.end(), [n](int i){return i%n == 0;});

Behind the scenes, the lambda expression [n](int i){return i%n == 0;} forces the compiler to implement an unnamed functor class similar to is_multiple_of with some obvious advantages:

  1. It's much less verbose.
  2. It doesn't introduce a new name just for a temporary use, resulting in less name pollution.
  3. Frequently (not in this example, though) the name of the functor class is much less expressive than its actual code. Placing the code closer to where it's called improves code clarity.

The Closure Type

In the previous examples, our functor class was named is_multiple_of. Naturally, the functor class automatically implemented by the compiler has a different name. Only the compiler knows this type's name, and we can think of it as an unnamed type. For presentation purposes, it's called the "closure type," whereas the temporary object resulting from the lambda expression is the "closure object." The type anonymity is not an issue for std::count_if because this is a template function and, therefore, argument type deduction takes place.

Turning a function into a template is a way to make it accept lambda expressions as arguments. Consider, for instance, a scientific library that implements a root-finder; i.e., a function that takes a functor object f and returns a double value x such that f(x) = 0. The root-finder might be a template function:

template <class T>
double find_root(T const& f);

However, this might not be desirable due to a few well-known template weaknesses: The code must be exposed in header files, compiling time increases, and template functions can't be virtual.

Can find_root be a non-template function? If so, what would be its signature?

double find_root(??? const& f);

Argument type deduction for template functions is not a novelty of C++11. Nevertheless, the new standard introduces two keywords — auto and decltype — to support type deduction. (Note: auto was a keyword in C++03, but with a different meaning.) If we want to give a name to a closure object, then we can follow this example:

auto f = [](double x){ return x * x — 0.5; };

Furthermore, an alias for the closure type, say function_t, can be set by:

typedef decltype(f) function_t;

Unfortunately, function_t is set at the same scope as the lambda expression and, therefore, is invisible elsewhere. In particular, it can't be used in find_root's signature.

Now, the other important actor of our play enters the stage: std::function.

Related Reading

More Insights

Currently we allow the following HTML tags in comments:

Single tags

These tags can be used alone and don't need an ending tag.

<br> Defines a single line break

<hr> Defines a horizontal line

Matching tags

These require an ending tag - e.g. <i>italic text</i>

<a> Defines an anchor

<b> Defines bold text

<big> Defines big text

<blockquote> Defines a long quotation

<caption> Defines a table caption

<cite> Defines a citation

<code> Defines computer code text

<em> Defines emphasized text

<fieldset> Defines a border around elements in a form

<h1> This is heading 1

<h2> This is heading 2

<h3> This is heading 3

<h4> This is heading 4

<h5> This is heading 5

<h6> This is heading 6

<i> Defines italic text

<p> Defines a paragraph

<pre> Defines preformatted text

<q> Defines a short quotation

<samp> Defines sample computer code text

<small> Defines small text

<span> Defines a section in a document

<s> Defines strikethrough text

<strike> Defines strikethrough text

<strong> Defines strong text

<sub> Defines subscripted text

<sup> Defines superscripted text

<u> Defines underlined text

Dr. Dobb's encourages readers to engage in spirited, healthy debate, including taking us to task. However, Dr. Dobb's moderates all comments posted to our site, and reserves the right to modify or remove any content that it determines to be derogatory, offensive, inflammatory, vulgar, irrelevant/off-topic, racist or obvious marketing or spam. Dr. Dobb's further reserves the right to disable the profile of any commenter participating in said activities.

Disqus Tips To upload an avatar photo, first complete your Disqus profile. | View the list of supported HTML tags you can use to style comments. | Please read our commenting policy.