std :: function<>和标准函数指针? [英] Difference between std::function<> and a standard function pointer?

查看:310
本文介绍了std :: function<>和标准函数指针?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

std :: function<>和标准函数指针之间的区别是什么?

Whats the difference between std::function<> and a standard function pointer?

typedef std::function<int(int)> FUNCTION;
typedef int (*fn)(int);

它们是否是同样的东西?

Are they effectively the same thing?

推荐答案

函数指针是在C ++中定义的实际函数的地址。 std :: function 是一个包装器,可以容纳任何类型的可调用对象(看起来像函数的对象)。

A function pointer is the address of an actual function defined in C++. An std::function is a wrapper that can hold any type of callable object (objects that look like functions).

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 参数。

Here, std::function allows you to abstract away exactly what kind of callable object it is you are dealing with — you don't know it's FooFunctor, you just know that it returns void and has one int parameter.

一个真实的例子,这个抽象是有用的是当你使用C ++与另一种脚本语言。您可能希望设计一个界面,以通用方式处理C ++中定义的函数以及脚本语言中定义的函数。

A real-world example where this abstraction is useful is when you are using C++ together with another scripting language. You might want to design an interface that can deal with both functions defined in C++, as well as functions defined in the scripting language, in a generic way.

修改

std :: function 还可以找到 std :: bind 。这两个是一起使用时非常强大的工具。

Alongside std::function, you will also find std::bind. These two are very powerful tools when used together.

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 c传递给 func / code>参数,并将 b 设置为常量 5

In that example, the function object returned by bind takes the first parameter, _1, and passes it to func as the a parameter, and sets b to be the constant 5.

这篇关于std :: function&lt;&gt;和标准函数指针?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆