Welcome to our comprehensive guide on C++14 Generic Lambdas! This lesson is designed for both beginners and intermediates, so sit back, relax, and let's dive into the world of functional programming in C++. š”
Lambdas, or anonymous functions, are a modern feature of C++ that allows you to create small, one-off functions without having to name them. They are a powerful tool for writing cleaner, more efficient code.
[capture](parameters) -> return_type { function_body }This is the syntax for a lambda function in C++. Let's break it down:
[capture]: This is the capture clause, which defines what the lambda function can access from its surrounding context.(parameters): Just like a regular function, lambdas can take parameters.-> return_type: This is the return type of the lambda function. If not specified, the return type is auto.{ function_body }: This is the body of the lambda function, enclosed in curly braces {}.With C++14, we have the concept of generic lambdas, which allows us to specify template parameters for our lambdas. This makes them more versatile and reusable.
auto my_lambda = [](auto x, auto y) { return x + y; };In the example above, my_lambda is a generic lambda that takes two template parameters x and y and returns their sum. The auto keyword before the function signature allows the compiler to infer the types of x and y.
Let's create a generic lambda that sorts a std::vector of any type.
template <typename T>
void sort_vector(std::vector<T>& vec, const T& compare) {
std::sort(vec.begin(), vec.end(), [=](const T& a, const T& b) {
return compare(a, b) < 0;
});
}In this example, we have a function sort_vector that takes a std::vector and a comparison function. The lambda inside the std::sort function uses the comparison function to sort the vector.
Now, let's create another generic lambda that filters a std::vector based on a condition.
template <typename T>
std::vector<T> filter_vector(std::vector<T>& vec, const T& filter) {
std::vector<T> result;
for (const auto& item : vec) {
if (filter(item)) {
result.push_back(item);
}
}
return result;
}In this example, we have a function filter_vector that takes a std::vector and a filter function. The lambda inside the loop uses the filter function to decide whether to add an item to the result vector.
What is the return type of the following lambda function?