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
});
Answers to questions are automatically generated and may not have been reviewed.
An introduction to lambda expressions - a concise way of defining simple, ad-hoc functions