Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How I can pass callable object to function as parameter

In c++ standard library almost all algo function takes a callable object as a argument. Now I want to try this thing with my program. I opened the the headers for function like find_if or search_n() but could not understand much about how these callable object parameters are handled and off course how argument is passed to them especially for lambda object ( can bind() be used for lambdas, I dont know)


Can any one explain me how this thing works. Thanks in advance

like image 494
deeiip Avatar asked Mar 05 '13 23:03

deeiip


People also ask

How do you pass a Func as a parameter?

When calling a function with a function parameter, the value passed must be a pointer to a function. Use the function's name (without parentheses) for this: func(print); would call func , passing the print function to it.

Can you pass a function as a parameter in Python?

Functions can be passed around in Python. In fact there are functions built into Python that expect functions to be given as one or more of their arguments so that they can then call them later.

Can I call a function in the parameter of another function?

Functions, like any other object, can be passed as an argument to another function.

What is callable function in Python?

A python callable() function in Python is something that can be called. This built-in function checks and returns True if the object passed appears to be callable, otherwise False.


1 Answers

Just have a template parameter for the function-like type and take an argument of that type:

template <typename Function>
void foo(Function func) {
  // Use func like so
  func(10);
}

This is how the standard library algorithms do it. You could call it with a lambda like so:

foo([](int x) { std::cout << (x * 2) << std::endl; });

Of course, this requires that you specify in your documentation what kind of function you expect as the Function type (until we get (until we get Concepts). Should it be unary? Binary? What type arguments should it take? What should it return?

Alternatively, you can take a function of a specific type by using std::function:

int foo(std::function<int(char)> func) {
  return func('a');
}

This time, foo will only take function-like objects that take a char argument and return an int. There is one downside to this method, however, which is that the compiler is unlikely to inline any lambdas you pass as func.

The most basic way to take a function as an argument is with a function pointer:

int foo(int (*func)(char)) {
  return func('a');
}

However, this will only take function pointers (some lambdas can be converted to function pointers). It won't take functors or anything else of the sort.

like image 99
Joseph Mansfield Avatar answered Nov 15 '22 04:11

Joseph Mansfield