函数指针是C中定义的实际函数的地址 . std::function 是一个包装器,可以容纳任何类型的可调用对象(可以像函数一样使用的对象) .
struct FooFunctor
{
void operator()(int i) {
std::cout << i;
}
};
// Since `FooFunctor` defines `operator()`, it can be used as a function
FooFunctor func;
std::function f(func);
在这里, std::function 允许你抽象出你正在处理的是什么类型的可调用对象 - 你只知道它返回 void 并且有一个 int 参数 .
这个抽象很有用的一个真实例子就是当你将C与另一种脚本语言结合使用时 . 您可能希望设计一个接口,该接口可以通用方式处理C中定义的函数以及脚本语言中定义的函数 .
Edit: 绑定
除了 std::function ,您还可以找到 std::bind . 这两个是一起使用时非常强大的工具 .
void func(int a, int b) {
// Do something important
}
// Consider the case when you want one of the parameters of `func` to be fixed
// You can used `std::bind` to set a fixed value for a parameter; `bind` will
// return a function-like object that you can place inside of `std::function`.
std::function f = std::bind(func, _1, 5);
在该示例中, bind 返回的函数对象接受第一个参数 _1 ,并将其作为 a 参数传递给 func ,并将 b 设置为常量 5 .