c++lambda

How can you pass lambda expressions to functions?


Suppose I have a custom container class with a selection function like below:

template <typename T>
class Container {
public:
    // ...
    
    Container<T> select(bool (*condition)(const T&)) const;

    // ...
};

As you can see, the select function takes a pointer to a condition function. This is a function that defines which items should be selected. So, an example use of this would be something similar to:

bool zero_selector(const int& element) {
    return (element == 0); // Selects all elements that are zero
}

Now if I have a container filled with, say s = { 1, 1, 0, 0, 1, 0, 1, 0 }, I could select a subset of these that would only contain zeroes using:

t = s.select(&zero_selector); // t = { 0, 0, 0, 0 }

This is a bit clunky, and lambda expressions would make this much more elegant:

t = s.select([&] (int x) -> bool { return (x == 0); });

Is this possible? If so, what should my function prototype be for Container::select() to accept a lambda as one of its parameters?

If not, then how is something like std::for_each implemented that can use a lambda expression as one of its arguments? Everything I've found just gives examples of lambda functions and using std::function<> to pass them as parameters, but nothing explains how std::for_each works with lambda expressions.

Note that this code is for demonstration purposes only. I have tried implementing the same principles in the actual project and it doesn't work.


Solution

  • You need to declare your lambda as stateless (that is, with an empty capture specification [](int x)-> bool {...}) for it to be convertable to a function pointer.