Skip to main content
  1. Posts/

c++11 function 与bind 学习笔记

·315 words·1 min
Note: This article is available in Chinese only. 本文暂无英文版本。 View original

C++11 std::function 是一种通用、多态的函数封装,它的实例可以对任何可 以调用的目标实体进行存储、复制和调用操作

见下面的例子

 1    /* ***********************************************
 2    Author :111qqz
 3    mail: renkuanze@sensetime.com
 4    Created Time :2018年07月19日 星期四 17时41分00秒
 5    File Name :bind.cpp
 6    ************************************************ */
 7    #include <functional>
 8    #include <iostream>
 9    using namespace std;
10    float foo( int x,int y,int z){return x+y+z+1.;}
11    int main()
12    {
13    	function<int(int,int)>func = foo;
14    	int y = 10;
15    	function<int(int)>fun = [&]( int value)->int
16    	{
17    		return 1+value+y;
18    	};
19    	cout<<func(15,4,9)<<endl;
20    	cout<<fun(8)<<endl;
21    	return 0;
22    }

std::bind 则是用来绑定函数调用的参数的,它解决的需求是我们有时候可 能并不一定能够一次性获得调用某个函数的全部参数,通过这个函数,我们可以将 部分调用参数提前绑定到函数身上成为一个新的对象,然后在参数齐全后,完成调 用

看下面的例子:

 1
 2    #include <iostream>
 3    #include <functional>
 4    using namespace std;
 5    int FUN( int x,int y,int z)
 6    {
 7    	return x+y+z;
 8    }
 9    int main()
10    {
11    	using namespace std::placeholders;
12    	//int (*fp)(int ,int,int) = FUN;
13    	auto bindfoo = bind(FUN,_1,1,2);
14    	int ans = bindfoo(0);
15    	cout<<ans<<endl;
16    	return 0;
17    }

Related

gdb学习笔记

·235 words·1 min
用gdb调试c++的时候,需要添加-g编译选项add_compile_options(-g),并且关掉各种编译优化