Cocos2d-x学习笔记(十)CC_CALLBACK回调函数相关宏

时间:2023-03-09 19:03:11
Cocos2d-x学习笔记(十)CC_CALLBACK回调函数相关宏

这里加入一个插曲,是关于Cocos2d-x回调函数的。首先,让我们Cocos支持的回调函数宏有哪些,以及其原型:

// new callbacks based on C++11
#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__)

右上边,以上共4个回调函数宏。都是通过C++11新增加bind()实现的。原型如下:

template <class Fn, class... Args>
/* unspecified */ bind (Fn&& fn, Args&&... args);
with return type ()
template <class Ret, class Fn, class... Args>
/* unspecified */ bind (Fn&& fn, Args&&... args);

使用如下,见http://www.cplusplus.com/reference/functional/bind/?kw=bind

// bind example
#include <iostream> // std::cout
#include <functional> // std::bind // a function: (also works with function object: std::divides<double> my_divide;)
double my_divide (double x, double y) {return x/y;} struct MyPair {
double a,b;
double multiply() {return a*b;}
}; int main () {
using namespace std::placeholders; // adds visibility of _1, _2, _3,... // binding functions:
auto fn_five = std::bind (my_divide,,); // returns 10/2
std::cout << fn_five() << '\n'; // auto fn_half = std::bind (my_divide,_1,); // returns x/2
std::cout << fn_half() << '\n'; // auto fn_invert = std::bind (my_divide,_2,_1); // returns y/x
std::cout << fn_invert(,) << '\n'; // 0.2 auto fn_rounding = std::bind<int> (my_divide,_1,_2); // returns int(x/y)
std::cout << fn_rounding(,) << '\n'; // MyPair ten_two {,}; // binding members:
auto bound_member_fn = std::bind (&MyPair::multiply,_1); // returns x.multiply()
std::cout << bound_member_fn(ten_two) << '\n'; // auto bound_member_data = std::bind (&MyPair::a,ten_two); // returns ten_two.a
std::cout << bound_member_data() << '\n'; // return ;
}

关于##__VA_ARGS__见博客地址:http://www.cnblogs.com/zhujudah/archive/2012/03/22/2411240.html

至于__selector__和__target__应该是cocos自定义的东西;我在c99、c11中没有找到对应的东西。

而关于placehoders命名空间内容如下:

namespace placeholders
{
extern /* unspecified */ _1;
extern /* unspecified */ _2;
extern /* unspecified */ _3;
// ...
}