Basically I want to do this: Can I use a lambda function or std::function object in place of a function pointer?
clearly that is impossible for now for functions that expect a function pointer. However, it will work for a function that expects a functor ( I have done it before with stl's sort() function)
However, I don't know how to write a function that takes a functor as an argument!
Anyone?
One way to pass a functor is to make its type a template argument. A type by itself is not a functor, however, so the client function or class must create a functor object with the given type. This, of course, is possible only for class type functors, and it rules out function pointer types.
We cannot pass the function as an argument to another function. But we can pass the reference of a function as a parameter by using a function pointer. This process is known as call by reference as the function parameter is passed as a pointer that holds the address of arguments.
Functors are objects that behave as functions. They are class objects which can overload the function operator() and act as function themselves. They can encapsulate their own function which is executed when needed.
Just write the function to take an arbitrary type:
template <typename Func>
void foo(Func fun)
{
fun(...);
}
This will then work with function pointers, functors and lambdas all the same.
void f() {}
struct G
{
void operator()() {}
};
foo(&f); // function pointer
foo(G()); // functor
foo([]() { ... }); // lambda
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With