+-

参见英文答案 > Should I use std::function or a function pointer in C++? 5个
什么是std :: function<>之间的区别和标准函数指针?
什么是std :: function<>之间的区别和标准函数指针?
那是:
typedef std::function<int(int)> FUNCTION;
typedef int (*fn)(int);
它们实际上是一回事吗?
最佳答案
函数指针是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<void (int)> f(func);
在这里,std :: function允许你抽象出你正在处理的是什么类型的可调用对象 – 你不知道它是FooFunctor,你只知道它返回void并且有一个int参数.
这个抽象很有用的一个真实示例是当您将C与另一种脚本语言一起使用时.您可能希望设计一个接口,该接口可以通用方式处理C中定义的函数以及脚本语言中定义的函数.
编辑:绑定
除了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<void (int)> f = std::bind(func, _1, 5);
在该示例中,bind返回的函数对象获取第一个参数_1,并将其作为a参数传递给func,并将b设置为常量5.
点击查看更多相关文章
转载注明原文:c – std :: function <>和标准函数指针之间的区别? - 乐贴网