来源:https://www.cnblogs.com/bigosprite/p/11294264.html
作者:bigosprite
std::function可调用对象包装器
函数指针:与C语言一致; 类成员函数指针; 仿函数(functor):也成函数对象,重载 operator()
运算符的类/结构体对象;lambda表达式。
std::function基本用法
#include <iostream>
#include <functional> // std::function
// global function
void func(void) {
std::cout << __FUNCTION__ << std::endl;
}
class Foo {
public:
// class static function
static int foo_func(int a) {
std::cout << __FUNCTION__ << "(" << a << "):";
return a;
}
// class non-static member function
int foo_func_nonstatic(int a) {
std::cout << __FUNCTION__ << "(" << a << "):";
return a;
}
};
class Bar {
public:
// functor
int operator()(int a) {
std::cout << __FUNCTION__ << "(" << a << "):";
return a;
}
};
int main() {
// 传入合适函数签名给std::function模板参数即可绑定对应签名的
// 普通函数或
// 类静态成员函数或
// 借助std::bind绑定类非静态成员函数
std::function<void(void)> func1 = func;
std::function<int(int)> func2 = Foo::foo_func;
Foo foo;
std::function<int(int)> func3 = std::bind(&Foo::foo_func_nonstatic, &foo,
std::placeholders::_1);
// 然后,直接像函数一样调用
func1(); // func
std::cout << func2(1) << std::endl; // foo_func(1):1
std::cout << func3(11) << std::endl; // foo_func_nonstatic(11):11
// 当函数签名一致时,func2可像一个变量一样复用
// Bar重载了operator()即成为functor,可直接包装到std::function
Bar bar;
func2 = bar;
std::cout << func2(2) << std::endl; // operator()(2):2
// 也可绑定lambda表达式
auto func_lambda = [](int a){
std::cout << "bind lambda sample(" << a << ")" << std::endl;
};
func_lambda(3); // bind lambda sample(3)
return 0;
}
#include <iostream>
#include <functional> // std::function
// 任意可调用对象,如普通全局函数
void func_callback(int a) {
std::cout << __FUNCTION__ << ":Output, a=" << a << std::endl;
}
class Foo {
public:
explicit Foo(std::function<void(int)> cb)
:cb_(cb), a_(0){
}
~Foo() = default;
// setter
void set_a(int a) {
a_ = a;
}
void OutputCallback() {
cb_(a_);
}
private:
std::function<void(int)> cb_;
int a_;
};
int main() {
// 实例化Foo,并参数注入回调函数
// 处理
// 回调输出处理结果
Foo foo(func_callback);
foo.set_a(1);
foo.OutputCallback(); // func_callback:Output, a=1
return 0;
}
注:C++11提供的std::function可替代C语言中函数指针作为回调函数,前者是C++编程风格,后者是C编程风格。
// Cocos2dx new callbacks based on C++11
//
// __selector__:回调函数指针
// __target__:回调对象指针
// ##__VA_ARGS__:可变参数列表
// std::placeholders::_1:不定参数1,调用时由调用函数的参数传入
// std::placeholders::_2:不定参数2,调用时由调用函数的参数传入
// std::placeholders::_3:不定参数3,调用时由调用函数的参数传入
#define CC_CALLBACK_0(__selector__,__target__, ...) std::bind(&__selector__,__target__, ##__VA_ARGS__)
#define CC_CALLBACK_1(__selector__,__target__, ...) std::bind(&__selector__,__target__, std::placeholders::_1, ##__VA_ARGS__)
#define CC_CALLBACK_2(__selector__,__target__, ...) std::bind(&__selector__,__target__, std::placeholders::_1, std::placeholders::_2, ##__VA_ARGS__)
#define CC_CALLBACK_3(__selector__,__target__, ...) std::bind(&__selector__,__target__, std::placeholders::_1, std::placeholders::_2, std::placeholders::_3, ##__VA_ARGS__)
文章转载自CPP开发前沿,如果涉嫌侵权,请发送邮件至:contact@modb.pro进行举报,并提供相关证据,一经查实,墨天轮将立刻删除相关内容。




