函数指针&绑定: boost::functoin/std::function/bind

see link
http://blog.csdn.net/gw569453350game/article/details/50789253
https://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 
#include 
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/c++)