仿函数的优点在于:能在函数中关联某些状态。对于回调机制,这种优点可以带来功能上的提升,因为对于一个函数而言,我们能根据不同的参数来生成不同的函数实例
#include<iostream>
using namespace std;
class A{
private:
int a;
public:
A(int i):a(i){};
int operator()()const{
return a;
}
};
void fun(const A& a){
cout << a() << endl;
}
int main(){
A a1(3);
fun(a1);
}
3
函数指针的封装:
#include<vector>
#include<iostream>
#include<cstdlib>
using namespace std;
//用于把函数指针封装成函数对象的封装类
template<int (*FUN)()>
class A{
public:
int operator()(){
return FUN();
}
};
int myRandom(){
return rand()%100;
}
//它使用由模板参数传递进来的函数对象类型
template<typename T>
void init(vector<int>& v){
T t;
srand(time(0));
for(size_t i=0;i<v.size();i++){
v[i] = t();
}
}
int main(){
vector<int> v(10);
init<A<myRandom> >(v);
cout << "ten random number:" << endl;
for(vector<int>::const_iterator iter = v.begin();
iter != v.end();
++iter){
cout << *iter << " ";
}
}
ten random number:
91 62 13 47 61 94 75 67 76 82