std::function的讲解与实战

一、C语言中的函数指针

先看一个函数指针的例子 test_fun.cpp:

#include<iostream>

//定义函数指针
typedef int (*func)();

using namespace std;

int test1(){
    cout<<"hello, test1"<<endl;
    return 0;
}

int test2(){
    cout<<"hello, test2"<<endl;
    return 0;
}

int main(int argc, char * argv[]){
    func fp = test1;
    fp();

    fp = test2;
    fp();

    return 0;
}

执行结果如下:

 二、std::function的作用

其实std::function的作用跟上面的函数指针类似。

但std::function的作用比函数指针更强大,应用场景更多。std::function是一个可调用的对象包装器,满足下列条件之一的是可调用对象:

(1)函数指针
(2)具有operator()成员函数的类对象(传说中的仿函数),lambda表达式
(3)可被转换为函数指针的类对象
(4)类成员(函数)指针
(5)bind表达式或其它函数对象

在实际编程时,主要有以下场景:

(1)绑定一个函数(普通函数或者静态函数)
(2)实现回调函数
(3)作为函数入参

三、几个例子

1、绑定一个函数

#include <iostream>
#include <functional>

using namespace std;

int test1(){
    cout<<"hello, test1"<<endl;
    return 0;
}

int main(int argc, char * argv[]){
    std::function<int(void)> fr_test1 = test1;
	fr_test1();

    return 0;
}

2、作为回调函数

#include <iostream>
#include <functional>

using namespace std;

class A{
    function<void()> callback;

public:
    A(){};
	
    A(const function<void()>& f) : callback(f) {};
	
	void notify(void){
		callback();
	}
	
	void init(const function<void()>& f){
	    callback = f;
	}
};

class Foo {
public:
    // Foo foo;
	// foo(); //此时会执行operator()方法
    void operator()(void) {
        cout << __FUNCTION__ << endl;
    }
};

void test(){
    cout << "test()" << endl;;
}

int main(void)
{
  Foo foo;
  
  A aa(foo);
  aa.notify();
  
  A bb;
  bb.init(test);
  bb.notify();
}

3、作为函数入参

#include <iostream>
#include <functional>

using namespace std;

void call_when_even(int x, const std::function<void(int)>& f) {
    if (!(x & 1)) {
        f(x);
    }
}

void output(int x) {
    cout << x << " ";
}

int main(void){
    for (int i = 0; i < 10; ++i) {
        call_when_even(i, output);
    }
	
	cout<<endl;
	
    return 0;
}

参考:

(1)深入浅出C++的function

(2)c++11新特性之std::function和lambda表达式

猜你喜欢

转载自blog.csdn.net/mars21/article/details/131468447