扩展 C++11中的std::bind
创建菜单项
int a = 1;
auto menuItem1 = MenuItemImage::create("CloseNormal.png","CloseSelected.png", CC_CALLBACK_1(Chapter2_4::itemClickHandler, this, a));
void Chapter2_4::itemClickHandler(Ref* pSender, int a) {
log("item click...");
log("a:%d", a);
}
auto menuItem2 = MenuItemImage::create("CloseNormal.png","CloseSelected.png", (std::function<void(Ref*)>)std::bind(test_func_xxx,std::placeholders::_1,2));
menuItem2->setPosition(origin + Vec2(0,- menuItem1->getContentSize().height * 1.5));
void test_func_xxx(Ref* sender,int b) {
log("test b: %d",b);
}
auto label1 = Label::createWithSystemFont("菜单三", "楷体", 26);
auto menuItem3 = MenuItemLabel::create(label1, [&](Ref* sender) {
log("itemClickHandler...3");
log("data-a:%d",a);
});
模拟创建菜单项
#include <iostream>
#include <functional>
#include <windows.h>
using namespace std::placeholders;
class Test{
public:
Test(){}
~Test(){}
};
typedef std::function<void(Test*)> ccMenuCallback;
class MenuItem{
private:
std::string str;
ccMenuCallback _callback;
public:
MenuItem(std::string _s):str(_s){}
MenuItem(std::string _s,const ccMenuCallback& callback):str(_s){
_callback = callback;
_callback(new Test());
}
~MenuItem(){}
static MenuItem* create(std::string str,const ccMenuCallback& callback);
};
MenuItem* MenuItem::create(std::string _str,const ccMenuCallback& callback){
auto item = new (std::nothrow)MenuItem(_str,callback);
return item;
}
void func1(Test* sender, int b)
{
std::cout << " b: " << b << std::endl;
}
void func2( int b)
{
std::cout << " b: " << b << std::endl;
}
class MyClass{
public:
MyClass(){}
~MyClass(){}
bool init(){
auto menuItem4 = MenuItem::create("测试",std::bind(MyClass::func3,this,_1,32));
return true;
}
void func3(Test* p,int b)
{
std::cout << " b: " << b << std::endl;
}
};
int main(void)
{
auto menuItem1 = MenuItem::create("测试",std::bind(func1,_1,1));
auto menuItem2 = MenuItem::create("测试",std::bind(func2,2));
auto obj = MyClass();
auto menuItem3 = MenuItem::create("测试",std::bind(&MyClass::func3,obj,_1, 31));
obj.init();
printf("------------end---------------\n");
return 0;
}
待
类Ref
|