haha I’m not sure about that. Unfortunately I’m not an expert in this area and it it seems a little difficult to figure out exactly what is happening here. But I’ll try explain.
MenuItemImage::create can be provided a callback function and that callback function is a
ccMenuCallback&, which is a typedef for
std::function<void(Ref*)>. As you have noted,
CC_CALLBACK_1 is just a macro for a
std::bind call. So when the callback is set for your second code example, it is basically doing this:
std::function<void(Ref*)> callback = std::bind(&HelloWorld::callBack, this);
For some reason, even though
HelloWorld::callBack (in the second example) takes no parameters and the callback is called with a
Ref* object as a parameter (
_callback(this); in the
MenuItem class), this is still valid code that compiles and works.
So I assume what is happening is that the code is smart enough to pass the parameters that the function will accept and then discard the rest. For example,
std::function<void(int, int)> func = std::bind(&HelloWorld::callBack, this, std::placeholders::_1); works with
HelloWorld::callBack(int). When the function is called, e.g.
func(100, 200), the first parameter (100) is passed to the function and the second parameter (200) is just ignored. So when you do this with your
MenuItemImage callback, the
Ref* object that is sent is just ignored.
std::bind like this doesn’t seem like a very good idea. It sounds like the sort of thing people would say is a “bad coding practice”. I don’t know if there are any actual problems with using it, e.g. worse performance, but at the very least it hides the fact that the function is being sent a
An example of why this is bad is that I think that the point of the
Ref* parameter is that it is providing you the
MenuItem object that is making the callback, allowing you to easily know which object sent the callback and to allow you to easily use that object. If you use the
std::bind way so your function doesn’t have to take a
Ref* then you might forget that the
Ref* object is being sent. If you do forget, if you ever need to know which object sent the callback, you may use some other, less convenient and/or less efficient way to figure out which object sent the callback. But that’s just what I think.