Why do we use std::function in C++ rather than the original C function pointer?

Michael Dorst picture Michael Dorst · Jul 5, 2012 · Viewed 17.9k times · Source

What is the advantage of std::function<T1(T2)> over the original T1 (*)(T2)?

Answer

Xeo picture Xeo · Jul 5, 2012

std::function can hold more than function pointers, namely functors.

#include <functional>

void foo(double){}

struct foo_functor{
  void operator()(float) const{}
};

int main(){
  std::function<void(int)> f1(foo), f2((foo_functor()));
  f1(5);
  f2(6);
}

Live example on Ideone.

As the example shows, you also don't need the exact same signature, as long as they are compatible (i.e., the parameter type of std::function can be passed to the contained function / functor).