Callable Object(可被调用对象)
可被某种方式调用某些函数的对象
- 一个函数,接受额外传入的args作为参数(argument)
- 一个指向成员函数的指针,当通过对象调用时该对象被传递为第一实参(必须为reference或pointer),其他实参对应成员函数的参数
- 一个函数对象(function object,拥有operator()),附带的args被传递作为实参
- 一个lambda(本质为函数对象)
示例如下:
void func(int x, int y);
auto lam = [](int x, int y) {
...
};
class C {
public:
void operator() (int x, int y) const;
void memfunc(int x, int y) const;
};
int main() {
C c_obj;
std::shared_ptr<C> sp(new C);
//bind() use callable objects to bind arguments
std::bind(func, 77, 33)(); //普通函数
std::bind(lam, 77, 33)(); //lambda
std::bind(C(),77, 33); //C::operator()(77,33)
std::bind(&C::memfunc, c_obj, 77,33);//c_obj.operator()(77, 33)
std::bind(&C::memfunc, sp,77,33); //sp->memfunc(77,33)
//async异步调用
std::async(func, 77, 33);
std::async(lam, 77, 33);
std::async(c_obj, 77, 33);//c_obj.operator()(77, 33)
std::async(&C::memfunc, &c_obj, 77, 33);//c_obj.memfunc(77,33)
std::async(&C::memfunc, sp, 77, 33);//sp->memfunc(77,33)
}
Function Type Wrapper(外覆器)
Class std::function<>于<functional>
e.g
void func(int x, int y);
//initialize collections of tasks
std::vector<std::function<void(int, int)>> tasks;
tasks.push_back(func);
tasks.push_back([](int x, int y) {
....
});
//call each task
for(std::function<void(int, int)> f : tasks) {
f(33, 66);
}
//使用成员函数()
class C {
public:
void memfunc(int x, inty) const;
};
std::function<void(const C&, int, int)> mf;
mf = &C::memfunc;
mf(C(), 42, 77);