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 (2)    

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,10,2);               // returns 10/2

  std::cout << fn_five() << '\n';                          // 5



  auto fn_half = std::bind (my_divide,_1,2);               // returns x/2

  std::cout << fn_half(10) << '\n';                        // 5



  auto fn_invert = std::bind (my_divide,_2,_1);            // returns y/x

  std::cout << fn_invert(10,2) << '\n';                    // 0.2



  auto fn_rounding = std::bind<int> (my_divide,_1,_2);     // returns int(x/y)

  std::cout << fn_rounding(10,3) << '\n';                  // 3



  MyPair ten_two {10,2};



  // binding members:

  auto bound_member_fn = std::bind (&MyPair::multiply,_1); // returns x.multiply()

  std::cout << bound_member_fn(ten_two) << '\n';           // 20



  auto bound_member_data = std::bind (&MyPair::a,ten_two); // returns ten_two.a

  std::cout << bound_member_data() << '\n';                // 10



  return 0;

}

关于##__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;

  // ...

}

你可能感兴趣的:(cocos2d-x)