Lambdas

Using Lambdas in Template Functions

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

Abstract art representing computer programming

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.

A computer programmer
Part of the course:

Professional C++

Comprehensive course covering advanced concepts, and how to use them on large-scale projects.

Free, unlimited access

This course includes:

  • 125 Lessons
  • 550+ Code Samples
  • 96% Positive Reviews
  • Regularly Updated
  • Help and FAQ
Free, Unlimited Access

Professional C++

Comprehensive course covering advanced concepts, and how to use them on large-scale projects.

Screenshot from Warhammer: Total War
Screenshot from Tomb Raider
Screenshot from Jedi: Fallen Order
Contact|Privacy Policy|Terms of Use
Copyright © 2024 - All Rights Reserved