3.2回调函数问题,一直没搞懂,求助!

首先我自己梳理下自己了解的部分,如果有误,望大家指出。

static CallFunc * create(const std::function<void()>& func)
我的理解是callFunc无返回值。
CC_CALLBACK_0表示它调用的是一个无参函数

于是我想试试我给它调用一个有参函数会怎样

void HelloWorld::test(Node *node){
log("%d",node->getTag());
}

bool HelloWorld::init()
{
CallFunc *call1=CallFunc::create(CC_CALLBACK_0(HelloWorld::test,this,this));
this->runAction(call1);

//等价上面
CallFunc *call2=CallFunc::create(bind(&HelloWorld::test, this,this));
this->runAction(call2);
//callFuncN

CallFuncN *call3=CallFuncN::create(CC_CALLBACK_0(HelloWorld::test,this,this));
this->runAction(call3);

return true;
}

打印的结果是:
-1
-1
-1

既然CallFunc和CallFuncN 都能调用参数,那么它们之间有什么区别?
而CC_CALLBACK_1 CC_CALLBACK_2 CC_CALLBACK_3 这有什么作用呢?

我从google得知 arg_list里可以包含占位符,我估计和CC_CALLBACK_1有关。

希望有懂的朋友,能写段小代码 让我验证一下,我有点晕了。。。

认真学一下C++11,你先看一下CC_CALLBACK_1这个宏是怎么实现的,很多就懂了

我比较了下CallFunc 和CallFuncN
/** creates the action with the callback of type std::function<void()>.
This is the preferred way to create the callback.
* When this funtion bound in js or lua ,the input param will be changed
* In js: var create(var func, var this, var ) or var create(var func)
* In lua:local create(local funcID)
*/
static CallFunc * create(const std::function<void()>& func);

/** creates the action with the callback of type std::function<void()>.
 This is the preferred way to create the callback.
 */
static CallFuncN * create(const std::function<void(Node*)>& func);

他们的区别在于一个有没有传值,而一个传递Node

CallFunc * CallFunc::create(const std::function<void()> &func)
{
CallFunc *ret = new CallFunc();

if (ret && ret->initWithFunction(func) ) {
    ret->autorelease();
    return ret;
}

CC_SAFE_DELETE(ret);
return nullptr;

}

CallFuncN * CallFuncN::create(const std::function<void(Node*)> &func)
{
auto ret = new CallFuncN();

if (ret && ret->initWithFunction(func) ) {
    ret->autorelease();
    return ret;
}

CC_SAFE_DELETE(ret);
return nullptr;

}

但依旧没发现区别。。。。

const std::function<void()> &func, 这个,你看懂了吗?不要着急,认真看看function 和bind

这个是c++11的新特性std::function和std::bind,我地理解是这样的。
static CallFuncN * create(const std::function<void(Node*)>& func);
function<void (Node *)>这个function是个模板,要求调用的函数是返回值为void,参数是node,所以bind绑定的时候绑定的函数就应该是这个类型的,按照正常的做法我们使用的是CC_CALLBACK_1这个宏定义,然后我们进入这个宏定义看看是怎么实现的,它的实现如下:
#define CC_CALLBACK_1(selector,target, …) std::bind(&selector,target, std::placeholders::_1, ##VA_ARGS)
也就是说他是用bind来实现的,这个bind的几个参数的含义是,第一个是要绑定的函数,如果bind绑定的是类的成员函数,那么第二个参数就咬告诉你用的是哪个实例的函数,这也就是我们一般第二个参数传入this的原因了,因为我们的回调函数写在类中,而调用的也是this的回调函数。第三个参数是占位符,意思是说这个位置我已近占用了,你不可以绑定第一个参数,剩下的就是你要绑定的参数数组了。通过bind绑定以后就产生了一个全新的函数,这个函数就像这样void HelloWorld::test(Node *node)。我们如果使用CC_CALLBACK_0的话,调用的时候就应该加上一个参数,比如this,这个时候通过bind绑定产生的函数是void HelloWorld::test();
这么说不知道你是否理解的明白,具体的可以搜索一下bind和function。