C++11 std::function和bind

std :: function is callable wrapper, its most important function is to achieve delay call:

// 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 to call the object and its parameters will be bound together. After binding can use std :: function to save, and we need to delay the call:

  (1) The binding parameters callable thereto into a functor;

  (2) some parameters can be bound.

  When the binding part of the parameters by using std :: placeholders to decide gap parameters will be the first of several parameters when calling occurs.

// 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
请按任意键继续. . .
*/

 

Published 257 original articles · won praise 22 · views 90000 +

Guess you like

Origin blog.csdn.net/qq_24127015/article/details/104891625