boost::functoin/std::function可用于所有 () operator
操作的对象(函数,类,成员函数,lambda表达式等等)。用处就是可以使用一个函数指针调用不用的函数实体(只要他们的signature一样),实现回调函数,或者多种不同的算法等等。
很好的例子:原文链接
#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 );
}
时间: 2024-11-06 07:35:29