6

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

deeiip
  • 3,319
  • 2
  • 22
  • 33

2 Answers2

14

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.

Joseph Mansfield
  • 108,238
  • 20
  • 242
  • 324
0

All algorithm function must get some functions to test the algo like find_if have to know which predicate you want to test on the loop. All std lib works with template and you can pass your function test as callable object. Callable object are object that have overload operator(), with it, std lib will call your sent object with some parameter and get up a return value if necessary. You can find which parameters and return values that are needed on some site, specialy I always use http://www.cplusplus.com/ you can find many documentation on all std lib in reference menu.

Special exemple from you : http://www.cplusplus.com/reference/algorithm/find_if/ find_if will take 2 iterators, one as first and an other as last, and a callable object that will take a object pointed by your iterator and return a bool.

Hulor
  • 219
  • 1
  • 5