Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to write a function that takes a functor as an argument

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?

like image 716
aCuria Avatar asked Oct 16 '11 21:10

aCuria


People also ask

How do you pass a functor as a template parameter?

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.

How do you send a function as an argument?

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.

Is a functor a function?

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.


1 Answers

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
like image 138
Peter Alexander Avatar answered Sep 27 '22 22:09

Peter Alexander