I was practicing with lambdas and came across the following code:
auto make_fibo() {
return [](int n) {
std::function<int(int)> recurse;
recurse = [&](int n) {
return (n <= 2) ? 1 : recurse(n - 1) + recurse(n - 2);
};
return recurse(n);
};
}
I did not know what it was function
or how it worked after searching and reading several texts, for example the following:
http://www.cplusplus.com/reference/functional/function/
My question is yes, it std::function
is similar to the following for example:
typedef int (*FredMemFn)(int i);
The answer is yes. The point is that function<> is capable of handling more cases than just being a simple pointer to a function. For example, it can also cover the case of functor , that is, the case of a class with the operator () overloaded. Take a look at the following code:
You have the code here: http://ideone.com/5lALLH I hope you find it useful.
std::function
is a class that wraps any element that can be called, for example:Pointers to functions (what is mentioned in the question).
Objects of a class that have the operator
()
overloaded.Lambda expressions.
bind expressions (
std::bind
, basically a function pointer with one or more predefined arguments).Source: cppreference.com - std::function
Note that template functions are not callable as such, only a particular instance of a template function with a type already attached can be combined with a
std::function
.