std::function与std::bind 函数指针

c++functionbind
function模板类和bind模板函数,使用它们可以实现类似函数指针的功能,但却却比函数指针更加灵活,特别是函数指向类 的非静态成员函数时。

std::function可以绑定到全局函数/类静态成员函数(类静态成员函数与全局函数没有区别),如果要绑定到类的非静态成员函数,则需要使用std::bind。


[cpp] view plaincopy
1. #include
2. #include
3. usingnamespacestd;
4.
5. typedefstd::function<void()> fp;
6. voidg_fun()
7. {
8. cout<<"g_fun()"<<endl;
9. }
10. classA
11. {
12. public:
13. staticvoidA_fun_static()
14. {
15. cout<<"A_fun_static()"<<endl;
16. }
17. voidA_fun()
18. {
19. cout<<"A_fun()"<<endl;
20. }
21. voidA_fun_int(inti)
22. {
23. cout<<"A_fun_int() "<<i<<endl;
24. }
25.
26. //非静态类成员,因为含有this指针,所以需要使用bind
27. voidinit()
28. {
29. fp fp1=std::bind(&A::A_fun,this);
30. fp1();
31. }
32.
33. voidinit2()
34. {
35. typedefstd::function<void(int)> fpi;
36. //对于参数要使用占位符 std::placeholders::_1
37. fpi f=std::bind(&A::A_fun_int,this,std::placeholders::_1);
38. f(5);
39. }
40. };
41. intmain()
42. {
43. //绑定到全局函数
44. fp f2=fp(&g_fun);
45. f2();
46.
47. //绑定到类静态成员函数
48. fp f1=fp(&A::A_fun_static);
49. f1();
50.
51. A().init();
52. A().init2();
53. return0;
54. }


同时,std::bind绑定到虚函数时会表现出多态行为。


[cpp] view plaincopy
1. #include
2. #include
3. usingnamespacestd;
4.
5. typedefstd::function<void()> fp;
6.
7. classA
8. {
9. public:
10. virtualvoidf()
11. {
12. cout<<"A::f()"<<endl;
13. }
14.
15. voidinit()
16. {
17. //std::bind可以表现出多态行为
18. fp f=std::bind(&A::f,this);
19. f();
20. }
21. };
22. classB:publicA
23. {
24. public:
25. virtualvoidf()
26. {
27. cout<<"B::f()"<\
28. \}\
29. \};\
30. \\int\\main()\\
31. \{\
32. \A* pa=\new\\B;\\
33. \pa->init();
34.
35. return0;
36. }
原文链接: https://www.cnblogs.com/Anzhongliu/p/6091998.html

欢迎关注

微信关注下方公众号,第一时间获取干货硬货;公众号内回复【pdf】免费获取数百本计算机经典书籍

原创文章受到原创版权保护。转载请注明出处:https://www.ccppcoding.com/archives/220318

非原创文章文中已经注明原地址,如有侵权,联系删除

关注公众号【高性能架构探索】,第一时间获取最新文章

转载文章受原作者版权保护。转载请注明原作者出处!

(0)
上一篇 2023年2月13日 上午10:52
下一篇 2023年2月13日 上午10:52

相关推荐