Is std :: function equivalent to a pointer?

13

I was practicing with lambdas and I found 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 it was function or how I worked after searching and reading several texts, for example the following:

link

My question is yes, std::function is similar to the following, for example:

typedef  int (*FredMemFn)(int i);
    
asked by Angel Angel 05.11.2015 в 01:26
source

2 answers

17

The answer is yes. The point is that function is capable of handling more cases than 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. Look at the following code:

#include <iostream>
#include <functional>
using namespace std;

int doble(int x) {
    return x * 2;
}

class Doblador {
public:
    int operator()(int x) {
        return x * 2;
    }
};

int main() {
    Doblador d;
    function<int(int)> f = doble;

    cout << "Doble de 2 = " << f( 2 ) << endl;

    f = d;
    cout << "Doble de 2 = " << f( 2 ) << endl;

    return 0;
}

You have the code here: link I hope you find it useful.

    
answered by 01.12.2015 / 21:18
source
2

std::function is a class that wraps to any element that can be invoked, for example:

  • Function pointers (what is mentioned in the question).

  • Objects of a class that has the operator% co_of% overloaded.

  • Lambda expressions.

  • Expressions bind ( () , basically a pointer to function with one or more predefined arguments in advance).

Source: cppreference.com - std :: function

Note that the "template" functions are not invoked as such, only a particular instance of a template function with an already associated type can be combined with a std::bind .

    
answered by 03.12.2015 в 16:06