cocos new 出新的项目之后,仔细阅读代码,才发现了一句3.0区别于2.0的代码:

auto closeItem = MenuItemImage::create(
"CloseNormal.png",
"CloseSelected.png",
                          CC_CALLBACK_1(HelloWorld::menuCloseCallback, this));

2.0内的代码用的不是CC_CALLBACK_1而是menu_selector.

CC_CALLBACK系列是3.0基于c++11的特性新增的。CC_CALLBACK系列的定义如下:

// 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__)

可以看出,CC_CALL_BACK系统后的数字,表示函数指针的参数个数。明白了这一点,选择CC_CALLBACK时,就不会出错鸟。

而看示例代码时,还会发现一个有意思的使用方法:

listener->onTouchesBegan = CC_CALLBACK_2(Layer::onTouchesBegan, this);

此时不禁要问onTouchesBegan又是啥,为啥不能直接函数指针赋值呢?

看定义就能明白了

std::function<void(const std::vector<Touch*>&, Event*)> onTouchesBegan;

因为CC_CALLBACK系列是std::bind,而onTouchesBegan是std::function来定义的。那么std::bind和std::function又有什么区别呢?

有博文说:

function模板类和bind模板函数,使用它们可以实现类似函数指针的功能,但却比函数指针更加灵活,特别是函数指向类的非静态成员函数时。

std::function可以绑定到全局函数/类静态成员函数(类静态成员函数与全局函数没有区别),如果要绑定到类的非静态成员函数,则需要使用std::bind。

标准库函数bind()和function()定义于头文件<functional>中(该头文件还包括许多其他函数对象),用于处理函数及函数参数。

std::bind绑定器

  • 将函数、成员函数和闭包转成function函数对象
  • 将多元(n>1)函数转成一元函数或者(n-1)元函数。

bind()接受一个函数(或者函数对象,或者任何你可以通过"(...)"符号调用的事物),生成一个其有某一个或多个函数参数被“绑定”或重新组织的函数对象。(译注:顾名思义,bind()函数的意义就像它的函数名一样,是用来绑定函数调用的某些参数的。)例如:

int f(int, char, double);
auto ff = bind(f, _1, 'c', 1.2); // 绑定f()函数调用的第二个和第三个参数,返回一个新的函数对象为ff,它只带有一个int类型的参数
int x = ff();     // f(7, 'c', 1.2);

参数的绑定通常称为"Currying"(译注:Currying---“烹制咖喱烧菜”,此处意指对函数或函数对象进行加工修饰操作), "_1"是一个占位符对象,用于表示当函数f通过函数ff进行调用时,函数ff的第一个参数在函数f的参数列表中的位置。第一个参数称为"_1", 第二个参数为"_2",依此类推。例如:

int f(int, char, double);
auto frev = bind(f, _3, _2, _1); // 翻转参数顺序
int x = frev(1.2, 'c', ); // f(7, 'c', 1.2);

此处,auto关键字节约了我们去推断bind返回的结果类型的工作。
    我们无法使用bind()绑定一个重载函数的参数,我们必须显式地指出需要绑定的重载函数的版本:

int g(int);
double g(double); auto g1 = bind(g, _1);      // 错误:调用哪一个g() ?
auto g2 = bind( (double(*)(double))g, _1); // 正确,但是相当丑陋
void H(int a);
//绑定全局函数
auto f11 = std::bind(H, std::placeholders::_1);
auto的类型实际上是std::function<void(int)> //绑定带参数的成员函数
std::function<void (char*, int)> f = std::bind(&ReadHandler::ConnectPreProcess, this, std::placeholders::_1, std::placeholders::_1); //三元函数转换成一元函数
int f(int, char, double);
// 绑定f()函数调用的第二个和第三个参数,
// 返回一个新的函数对象为ff,它只带有一个int类型的参数
auto ff = bind(f, _1, ‘c’, 1.2);
int x = ff();

自己写代码示例如下:

int Func(int x, int y);
auto bf1 = std::bind(Func, , std::placeholders::_1);
bf1(); ///< same as Func(10, 20) int HelloWorld::AddFunc( int a, int b )
{
return a + b;
} bool HelloWorld::init()
{ auto bf2 = std::bind(&HelloWorld::AddFunc,this , std::placeholders::_1, std::placeholders::_2 );
auto result1 = bf2(, ); ///< same as a.Func(10, 20) std::function< int(int)> bf3 = std::bind(&HelloWorld::AddFunc, this, std::placeholders::_1, );
auto result2 = bf3(); ///< same as a.Func(10, 100) }

上面的例子中,bf1是把一个两个参数普通函数的第一个参数绑定为10,生成了一个新的一个参数的可调用实体体; bf2是把一个类成员函数绑定了类对象,生成了一个像普通函数一样的新的可调用实体; bf3是把类成员函数绑定了类对象和第二个参数,生成了一个新的std::function对象。看懂了上面的例子,下面我们来说说使用bind需要注意的一些事项:

  • (1)bind预先绑定的参数需要传具体的变量或值进去,对于预先绑定的参数,是pass-by-value的
  • (2)对于不事先绑定的参数,需要传std::placeholders进去,从_1开始,依次递增。placeholder是pass-by-reference的
  • (3)bind的返回值是可调用实体,可以直接赋给std::function对象
  • (4)对于绑定的指针、引用类型的参数,使用者需要保证在可调用实体调用之前,这些参数是可用的
  • (5)类的this可以通过对象或者指针来绑定

std::function

它是函数、函数对象、函数指针、和成员函数的包装器,可以容纳任何类型的函数对象,函数指针,引用函数,成员函数的指针。
以统一的方式处理函数、函数对象、函数指针、和成员函数。允许保存和延迟执行函数。

  • 函数和成员函数作为function

function是一个拥有任何可以以"(...)"符号进行调用的值的类型。特别地,bind的返回结果可以赋值给function类型。function十分易于使用。(译注:更直观地,可以把function看成是一种表示函数的数据类型,就像函数对象一样。只不过普通的数据类型表示的是数据,function表示的是函数这个抽象概念。)例如:

typedef std::function<float (int x, int y)> f ;// 构造一个函数对象,它能表示的是一个返回值为float,两个参数为int,int的函数
struct int_div { // 构造一个可以使用"()"进行调用的函数对象类型
float operator() (int x, int y) const { return ((float)x)/y; };
}; void HelloWorld::testing()
{
f f1= int_div(); // 赋值
auto result3 = f1( , );
}

成员函数可被看做是带有额外参数的自由函数:

struct int_div {        // 构造一个可以使用"()"进行调用的函数对象类型
float operator() (int x, int y) const { return ((float)x)/y; };
int int_div_fun( int x ){ return x; };
};
typedef std::function<int (int_div*, int)> f_2; bool HelloWorld::init()
{
f_2 f2 = std::mem_fn(&int_div::int_div_fun); // 指向成员函数 int_div int_div_object;
int v = f2(&int_div_object, ); // 在对象x上用参数5调用X::foo()
std::function<int (int)> ff = std::bind( f2, &int_div_object, std::placeholders::_1); // f的第一个参数是&x
v = ff(); // 调用x.foo(5) }

ps:被vs2012的bug给坑了。因为看网上的代码于是刚开始第9行是这么写的:f_2 f2 = &int_div::int_div_fun;

然后就报错误:Error 1 error C2664: 'std::_Func_class<_Ret,_V0_t,_V1_t>::_Set' : cannot convert parameter 1 from '_Myimpl *' to 'std::_Func_base<_Rx,_V0_t,_V1_t> *'

查了一下,vs2010没有这个编译错误,但是2012有。2012必须得加上std::mem_fn才能编译。

  • 可以用function取代函数指针。因为它可以保存函数延迟执行,所以比较适合作为回调函数,也可以把它看做类似于c#中特殊的委托,只有一个成员的委托。
  • struct int_div { // 构造一个可以使用"()"进行调用的函数对象类型
      float operator() (int x, int y) const { return ((float)x)/y; };
      int int_div_fun( int x ){ return x; };   int_div( std::function<void()>& f ):m_callback(f){};
      void Notify()
      {
        m_callback();
      }
      std::function<void()> m_callback;
    };
  • function还可以作为函数入参,这样可以在函数外部控制函数的内部行为了,让我们的函数变得更加灵活。
  • void Foo(int x, std::function<void(int)>& f)
    {
    if(x%==)
    f(x);
    } void G(int x)
    {
    cout<<x<<endl;
    } void H(int x)
    {
    cout<<x+<<endl;
    } void TestFoo()
    {
    auto f = std::bind(G, std::placeholders::_1);
    Foo(, f); //在Foo函数外面更改f的行为
    f = std::bind(H, std::placeholders::_1);
    Foo(, f);
    }

c++11中推出function是为了泛化函数对象,函数指针,引用函数,成员函数的指针,让我们可以按更统一的方式写出更加泛化的代码;推出bind是为了替换和增强之前标准库的bind1st和bind2st,让我们的用起来更方便!

C++ 11 std::function std::bind使用的更多相关文章

  1. c++11——std::function和bind绑定器

    c++11中增加了std::function和std::bind,可更加方便的使用标准库,同时也可方便的进行延时求值. 可调用对象 c++中的可调用对象存在以下几类: (1)函数指针 (2)具有ope ...

  2. C++11 学习笔记 std::function和bind绑定器

    C++11 学习笔记 std::function和bind绑定器 一.std::function C++中的可调用对象虽然具有比较统一操作形式(除了类成员指针之外,都是后面加括号进行调用),但定义方法 ...

  3. C++11学习笔记之三lamda表达式,std::function, std::bind

    //lamda //first lamda [] {}; // second lamda []() //or no need () when paramater is null { std::cout ...

  4. std::function,std::bind复习

    #include <iostream> #include <functional>//std::bind返回函数对象 void fun1(int a, int b) { std ...

  5. C++中的仿函数,std::function和bind()的用法

    1.仿函数:又叫std::function,是C++中的一个模板类 2.C语言中的函数指针: int  add(int a,int b) { return a+b; } typedef int (*f ...

  6. 利用C++11的function和bind简化类创建线程

    问题引出 当在类中需要创建线程时,总是因为线程函数需要定义成静态成员函数,但是又需要访问非静态数据成员这种需求,来做若干重复性的繁琐工作.比如我以前就经常定义一个静态成员函数,然后定一个结构体,结构体 ...

  7. C++11 中function和bind以及lambda 表达式的用法

    关于std::function 的用法:  其实就可以理解成函数指针 1. 保存自由函数 void printA(int a) { cout<<a<<endl; } std:: ...

  8. 【浅析C++11】std::function和std::bind

    目录 std::function可调用对象包装器 std::function基本用法 std::function/std::bind与抽象工厂.工厂方法的一点思考 std::function可调用对象 ...

  9. C/C++ C++ 11 std::function和std::bind用法

    std::bind() std::bind 主要用于绑定生成目标函数,一般用于生成的回调函数,cocos的回退函数都是通过std::bind和std::function实现的.两个点要明白: 1.绑定 ...

随机推荐

  1. java正则表达式简介

    Java的正则表达式讲解:(为了能看清,本文正则表达式用中文的句号代替英文句点) 1 英文句点符号:匹配单个任意字符. eg: 表达式”t.o  可以匹配:tno,t#o,teo等等.不可以匹配:tn ...

  2. margin和padding的学习

    你在学习margin和padding的时候是不是懵了--什么他娘的内边距,什么他娘的外边距.呵呵呵,刚開始我也有点不理解,后来通过查资料学习总算弄明确了,如今我来谈一下自己对margin和paddin ...

  3. linux sar命令详细说明相关参数

    详细说明linux的sar命令 sar(System Activity Reporter系统活动情况报告)是目前 Linux 上最为全面的系统性能分析工具之一,可以从多方面对系统的活动进行报告,包括: ...

  4. exception PLS-00103: Encountered the symbol "(" when expecting one of the following:

      exception PLS-00103: Encountered the symbol "(" when expecting one of the following: Cre ...

  5. SettingsSVNPlugin

      迁移时间:2017年5月20日11:24:50CreateTime--2016年9月18日17:53:20Author:Marydonmyeclipse/eclipse中配置svn插件参考链接:h ...

  6. webservice系统学习笔记3-分析wsdl文件的组成

    详细分析前面章节的服务的wsdl文件 1.http://localhost:8888/ws01?wsdl 2.http://localhost:8888/ws01?xsd=1 在接口服务中添加复杂类型 ...

  7. Eclipse c++ 编译调试

    直接添加源文件方法: 右键选择工程->import->General->File System,在弹出的对话框中选择源文件目录,筛选文件后: 1.如果直接加到工程中,点Finish就 ...

  8. k8s内核参数调优

    cat /etc/sysctl.conf kernel.core_uses_pid=1 kernel.pid_max=4194303 kernel.ctrl-alt-del=1 # kernel.co ...

  9. MySQL主从同步的一个小问题解决

    由于历史遗留问题,我们的MySQL主从库的表结构不一致,主库的某个表tableA比从库表tableA少了一个字段. 当尝试在主库上更改表结构时,这行alter语句会随着binlog同步到从库,如果从库 ...

  10. HDUOJ---汉洛塔IX

    汉诺塔IX Time Limit: 3000/1000 MS (Java/Others)    Memory Limit: 32768/32768 K (Java/Others)Total Submi ...