c++ - 为什么我们在 C++ 中使用 std::function 而不是原来的 C 函数指针?

std::function<T1(T2)>的优势是什么?超过原T1 (*)(T2) ?

最佳答案

std::function 可以容纳的不仅仅是函数指针,即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.

如示例所示,您也不需要完全相同的签名,只要它们兼容(即 std::function 的参数类型可以传递给包含的函数/仿函数)。

https://stackoverflow.com/questions/11352936/

相关文章:

c++ - 我真的需要为 const 对象实现用户提供的构造函数吗?

c++ - 架构 x86_64 : Compiling problems 的 undefined s

c++ - 标准的 atomic bool 和 atomic flag 之间的区别

c++ - 为什么 unique_ptr 实例化编译为比原始指针更大的二进制文件?

c++ - QObject 多重继承

c++ - C 和 C++ 标准之间的关系是什么?

c++ - 如何轻松查看 C/C++ #include 图?

c++ - 为 Windows 编写超薄 C++ 程序(如 uTorrent)

c++ - 在 C++ 中设置本地环境变量

c++ - 向 Python 公开 C++ API