zoukankan      html  css  js  c++  java
  • 函数指针&绑定: boost::functoin/std::function/bind

    see linkhttps://isocpp.org/wiki/faq/pointers-to-members
    function vs template: http://stackoverflow.com/questions/14677997/stdfunction-vs-template

    boost::functoin/std::function可用于全部 operator() 操作的对象(函数,类。成员函数。lambda表达式等等)。

    用处就是能够使用一个函数指针调用不用的函数实体(仅仅要他们的signature一样),实现回调函数。或者多种不同的算法等等。
    关于 std::function的实现。 see link:http://stackoverflow.com/questions/18453145/how-is-stdfunction-implemented
    非常好的样例:原文链接

    #include <functional>
    #include <iostream>
    using namespace std;
    
    std::function< int(int)> Functional;
    
    // 普通函数
    int TestFunc(int a)
    {
        return a;
    }
    
    // Lambda表达式
    auto lambda = [](int a)->int{ return a; };
    
    // 函数对象(functor)
    class Functor
    {
    public:
        int operator()(int a)
        {
            return a;
        }
    };
    
    // 1.类成员函数
    // 2.类静态函数
    class TestClass
    {
    public:
        int ClassMember(int a) { return a; }
        static int StaticMember(int a) { return a; }
    };
    
    int main()
    {
        // 普通函数
        Functional = TestFunc;
        int result = Functional(10);
        cout << "普通函数:"<< result << endl;
    
        // Lambda表达式
        Functional = lambda;
        result = Functional(20);
        cout << "Lambda表达式:"<< result << endl;
    
        // 仿函数
        Functor testFunctor;
        Functional = testFunctor;
        result = Functional(30);
        cout << "仿函数:"<< result << endl;
    
        // 类成员函数
        TestClass testObj;
        Functional = std::bind(&TestClass::ClassMember, testObj, std::placeholders::_1);
        result = Functional(40);
        cout << "类成员函数:"<< result << endl;
    
        // 类静态函数
        Functional = TestClass::StaticMember;
        result = Functional(50);
        cout << "类静态函数:"<< result << endl;
    
        return 0;
    }

    function简化了函数指针的使用:

    class FooClass {
    public:
         void Print( int a ) {
             std::cout << "A FooClass, param = "<< a <<" this = " << this << std::endl;
         }
    };
    
    void main() {
        FooClass *myFoo = new FooClass();
        void( FooClass::* oldFunc )(int) = &FooClass::Print; //C style function pointer
        (myFoo->*oldFunc)( 5 );
    
        boost::function newFunc = boost::bind( &FooClass::Print, myFoo, _1 ); //boost function      
        newFunc( 5 );
    }
  • 相关阅读:
    常用C# 6.0 常用 新特性
    VS 编译总是出现错误: "LC.EXE 已退出,代码为1"
    C# XML封装
    VS 2015秘钥
    写入Txt文本信息
    C# 7.0 新特性
    Winform 弹框增加确定按钮并点击确定后进行下一步操作
    VS 代码过长自动换行
    C# 6.0 新特性
    string::npos 是什么 c++ /STL
  • 原文地址:https://www.cnblogs.com/mengfanrong/p/5186058.html
Copyright © 2011-2022 走看看