C++11 std::function和bind

std::function是可调用对象的包装器,它最重要的功能是实现延时调用:

// threadTest.cpp : 定义控制台应用程序的入口点。
//
#include "stdafx.h"
#include <iostream>
#include <functional>
using namespace std;

void func(void)
{
	cout << __FUNCTION__ << "\n";
}

class Foo
{
public:
	static int foo_func(int a)
	{
		cout << __FUNCTION__ << "(" << a << ") ->: ";
		return a;
	}
};

class Bar
{
public:
	int operator()(int a)
	{
		cout<<__FUNCTION__ << "(" << a << ") ->: ";
		return a;
	}
};

int main()
{
	// 绑定一个普通函数
	std::function<void(void)> f1 = func;
	f1();

	// 绑定一个类的静态成员函数
	std::function<int(int)> f2 = Foo::foo_func;
	cout << f2(123) << endl;

	// 绑定一个仿函数
	Bar bar;
	f2 = bar;
	cout << f2(123) << endl;
    return 0;
}



//output
/*
func
Foo::foo_func(123) ->: 123
Bar::operator ()(123) ->: 123
请按任意键继续. . .
*/

std::bind用来将可调用对象与其参数一起进行绑定。绑定后可以使用std::function进行保存,并延迟到我们需要的时候调用:

  (1) 将可调用对象与其参数绑定成一个仿函数;

  (2) 可绑定部分参数。

  在绑定部分参数的时候,通过使用std::placeholders来决定空位参数将会是调用发生时的第几个参数。

// threadTest.cpp : 定义控制台应用程序的入口点。
//
#include "stdafx.h"
#include <iostream>
#include <functional>
using namespace std;

class A
{
public:
	int i_ = 0;// C++11允许非静态(non-static)数据成员在其声明处(在其所属类内部)进行初始化

	void output(int x, int y)
	{
		std::cout << x << " " << y << std::endl;
	}
};

int main()
{
	A a;
	// 绑定成员函数,保存仿函数
	std::function<void(int, int)> fr1 = std::bind(&A::output, &a, std::placeholders::_1, std::placeholders::_2);
	// 调用成员函数
	fr1(1, 2);

	std::function<void(int, int)> fr2 = std::bind(&A::output, &a, std::placeholders::_2, std::placeholders::_1);
	// 调用成员函数
	fr2(1, 2);

	// 绑定成员变量
	std::function<int&(void)> fr3 = std::bind(&A::i_, &a);
	fr3() = 100; // 对成员变量进行赋值
	std::cout << a.i_ << std::endl;
    return 0;
}



//output
/*
1 2
2 1
100
请按任意键继续. . .
*/
发布了257 篇原创文章 · 获赞 22 · 访问量 9万+

猜你喜欢

转载自blog.csdn.net/qq_24127015/article/details/104891625
今日推荐