zoukankan      html  css  js  c++  java
  • std::function与std::bind 函数指针

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

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

    1. #include <iostream>  
    2. #include <functional>  
    3. using namespace std;  
    4.   
    5. typedef std::function<void ()> fp;  
    6. void g_fun()  
    7. {  
    8.     cout<<"g_fun()"<<endl;  
    9. }  
    10. class A  
    11. {  
    12. public:  
    13.     static void A_fun_static()  
    14.     {  
    15.         cout<<"A_fun_static()"<<endl;  
    16.     }  
    17.     void A_fun()  
    18.     {  
    19.         cout<<"A_fun()"<<endl;  
    20.     }  
    21.     void A_fun_int(int i)  
    22.     {  
    23.         cout<<"A_fun_int() "<<i<<endl;  
    24.     }  
    25.   
    26.     //非静态类成员,因为含有this指针,所以需要使用bind  
    27.     void init()  
    28.     {  
    29.         fp fp1=std::bind(&A::A_fun,this);  
    30.         fp1();  
    31.     }  
    32.   
    33.     void init2()  
    34.     {  
    35.         typedef std::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. int main()  
    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.     return 0;  
    54. }  

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

    1. #include <iostream>  
    2. #include <functional>  
    3. using namespace std;  
    4.   
    5. typedef std::function<void ()> fp;  
    6.   
    7. class A  
    8. {  
    9. public:  
    10.     virtual void f()  
    11.     {  
    12.         cout<<"A::f()"<<endl;  
    13.     }  
    14.   
    15.     void init()  
    16.     {  
    17.         //std::bind可以表现出多态行为  
    18.         fp f=std::bind(&A::f,this);  
    19.         f();  
    20.     }  
    21. };  
    22. class B:public A  
    23. {  
    24. public:  
    25.     virtual void f()  
    26.     {  
    27.         cout<<"B::f()"<<endl;  
    28.     }  
    29. };  
    30. int main()  
    31. {  
    32.     A* pa=new B;  
    33.     pa->init();  
    34.   
    35.     return 0;  
    36. }  
  • 相关阅读:
    Redis "MISCONF Redis is configured to save RDB snapshots, but is currently not able to persist on disk"问题的解决
    素描
    python 标准库
    Python内置函数filter, map, reduce
    Python的lambda表达式
    python中super关键字的用法
    python一个注意的地方
    python中self,cls
    python中的实例方法、静态方法、类方法、类变量和实例变量
    python模块及包的导入
  • 原文地址:https://www.cnblogs.com/Anzhongliu/p/6091998.html
Copyright © 2011-2022 走看看