1. 可调用对象(Callable Objects)的定义
1. 是一个函数指针;
2. 是一个具有operator()成员函数的类对象(仿函数);
3. 是一个可被转换为函数指针的类对象;
4. 是一个类成员(函数)指针;
2. 可调用对象包装器——std::function
std::function是可调用对象的包装器,它是一个类模板,可以容纳除了类成员(函数)指针之外的所有可调用对象。通过指定它的模板参数,它可以用统一的方式处理函数、函数对象、函数指针,并允许保存和延迟执行他们。
2.1 std::function原型
template< class R, class... Args >
class function<R(Args...)>
R是返回值类型,Args是函数的参数类型,实例一个std::function对象很简单,就是将可调用对象的返回值类型和参数类型作为模板参数传递给std::function模板类。比如:
std::function<void()> f1;
std::function<int (int , int)> f2;
2.2 std::function的用法
2.2.1 基础用法
void Func1(void){
cout << "func1" << endl;
}
class Func2 {
public:
static int test_func(int i)
{
cout << "i = "<< i << endl;
return i;
}
};
//仿函数
class Func3
{
public:
int operator()(int a)
{
cout<<"a = "<<a<<enldl
return a;
}
};
int main()
{
std::function<void(void)> f1 = Func1; //普通函数
f1(); //调用
std::function<int(int)> f2 = Func2::test_func; //绑定静态成员函数
f2(1);
std::function<int(int)> f3 = Func3; //仿函数
f3(1);
return 0;
}
打印:
func1
i = 1
a = 1
2.2.2 函数包装器
class Func {
std::function<void()> tfn;
public:
Func(const std::function<void()>& f)
: tfn(f)
{
}
void Notify(void)
{
tfn();
}
};
class Foo
{
public:
void operator() (void)
{
cout << "Foo" << endl;
}
};
int main()
{
Foo foo;
Func f(foo);
f.Notify();
return 0;
}
打印:
Foo
2.2.3 作函数入参
void Func(const std::function<void()>& param)
{
param();
}
void Foo_test()
{
cout << "Foo" << endl;
}
int main()
{
Func(Foo_test);
return 0;
}
打印:
Foo
3. std::bind绑定器
std::bind用来将可调用对象与其参数一起进行绑定。绑定后的结果可以使用std::function保存,并延迟调用到任何我们需要的时候。
主要作用:
1) 将可调用对象与其参数一起绑定成一个仿函数;
2) 将多元(参数个数为n,n > 1)可调用对象转成一元或者(n-1)元可调用对象,即只绑定部分参数;
3.1 std::function和std::bind配合使用
class Func
{
public:
int test(int i, int j)
{
cout << "i + j = " << i + j << endl;
return i + j;
}
};
int main()
{
Func f;
auto tf = std::bind(&Func::test, &f, 1, 2); //std::function<int(int, int)>
tf(0, 0); //如果bind中传入具体参数,此处传值不起作用
return 0;
}
打印:
i + j = 3
部分参考书籍:深入应用c++ 代码优化与工程级应用