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

谁说胖子不能爱 提交于 2019-11-27 11:46:51

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).

std::function can hold function objects (including lambdas), as well as function pointers with the correct signature. So it is more versatile.

Shoe

Apart from the cleaner look and a more descriptive syntax, std::function can store any callable object:

  • functions
  • lambda expressions
  • bind expressions
  • functors

Not to mention that storing, copying, and binding objects to member functions is much easier and more intuitive.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!