C++: “auto” on anonymous functions

C++14 introduced an improvement to the way programmers can declare anonymous functions (a.k.a. lambda expressions).

For example, before C++14, if programmers wanted to pass an anonymous function to the sorting algorithm, they had to do something like this:

int main()
{
  std::vector<std::string> s = { "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday" };

  std::sort(s.begin(), s.end(), [](const std::string& a, const std::string& b)
  {
    return b < a; // descending order
  });

  for (auto& i : s) std::cout << i << "\n";
}

Since C++14, programmers can let the compiler deduce the types of the variables passed as parameters (using auto) in a lambda expression, so the example above can be rewritten as follows:

int main()
{
  std::vector<std::string> s = { "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday" };

  std::sort(s.begin(), s.end(), [](auto& a, auto& b)
  {
    return b < a; // descending order
  });

  for (auto& i : s) std::cout << i << "\n"
}

Notice that with this small improvement, the code looks simpler, it is more fluid to read, and the programmer can focus more on the algorithm than on the type definitions themselves, delegating the compiler to deal with those things.

While my example is trivial and only demonstrates cleaner code, when working with templates or complex data structures, using auto as a lambda expression argument can significantly enhance programmers’ lives by reducing errors and increasing productivity. As C++ continues to evolve, embracing these features can greatly enhance our programming experience.

More info about auto:

Leave a comment