see link: https://isocpp.org/wiki/faq/pointers-to-members
function vs template: http://*.com/questions/14677997/stdfunction-vs-template
boost::functoin/std::function可用于全部 operator()
操作的对象(函数,类。成员函数。lambda表达式等等)。
用处就是能够使用一个函数指针调用不用的函数实体(仅仅要他们的signature一样),实现回调函数。或者多种不同的算法等等。
关于 std::function的实现。 see link:http://*.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 );
}