Using Lambdas in Template Functions

How can I pass a lambda as an argument to a function template?

When passing a lambda as an argument to a function template, you can use auto as the parameter type. This allows the compiler to deduce the type of the lambda.

Here's an example:

#include <iostream>

template <typename T, typename Callback>
void Transform(T& Value, Callback Operation) {
  Operation(Value);
}

int main() {
  int Number{5};

  Transform(Number, [](auto& Value) {  
    Value *= 2;
  });

  std::cout << "Number: " << Number << '\n';
}
Number: 10

In this case, Transform is a function template that accepts a reference to a value of any type T, and a Callback which is deduced to be the type of the lambda we pass.

Inside main, we pass Number (an int) as the first argument, and a lambda that doubles its argument as the second. The lambda parameter Value is declared as auto&, which allows it to accept arguments of any type by reference.

When Transform is called, the lambda is invoked with Number as its argument, doubling its value.

This pattern is very powerful and flexible. For example, we could easily change the lambda to perform a different operation:

Transform(Number, [](auto& Value) {
  Value = Value * Value; // Square the value
});

Lambdas

An introduction to lambda expressions - a concise way of defining simple, ad-hoc functions

Questions & Answers

Answers are generated by AI models and may not have been reviewed. Be mindful when running any code on your device.

Capturing Class Members in Lambdas
How can I capture member variables of a class when defining a lambda inside a member function?
Returning Lambdas from Functions
Can I return a lambda from a function? If so, how do I specify the return type?
Using Lambdas as Comparators
Can I use a lambda as a comparator for STL containers and algorithms?
Creating Stateful Lambdas
Is it possible to create a lambda that maintains state across multiple invocations?
Creating Recursive Lambdas
Can a lambda call itself recursively?
Or Ask your Own Question
Get an immediate answer to your specific question using our AI assistant