2015-01-04 58 views
0

通常可以使用CC_CALLBACK_X來設置功能的回調在那裏只接受Ref* PARAM:如何使用cocos2dx中的參數設置回調?

//cocos2dx builtins 
#define CC_CALLBACK_1(__selector__,__target__, ...) std::bind(&__selector__,__target__, std::placeholders::_1, ##__VA_ARGS__) 
typedef std::function<void(Ref*)> ccMenuCallback; 
void MenuItem::setCallback(const ccMenuCallback& callback) 


//my code starts here 
MyClass::my_callback(Ref* sender) { ... }; 

MyClass::init() 
{ 
    auto menu = Menu::create(); 
    auto menuitem = MenuItem::create(); 
    menuitem->setCallback(CC_CALLBACK_1(MyClass::my_callback, this)); 
}; 

工作正常。

問題是我有一個回調我想用另一個參數,如int,我不知道如何得到它的工作。

MyClass::my_callback_with_param(Ref* sender, int arg1) { ... }; 
MyClass::my_callback_with_param_swapped(int arg1, Ref* sender) { ... }; 

//in the init func, I've tried stuff like 

int an_int = 2 
menuitem->setCallback(CC_CALLBACK_2(MyClass::my_callback_with_param, this, an_int)); 
//or changing the signature of the function 
menuitem->setCallback(CC_CALLBACK_2(MyClass::my_callback_with_param_swapped, an_int, this)); 
//or using std::bind (which I'm not very familiar with) 
menuitem->setCallback(CC_CALLBACK_1(std::bind(MyClass::my_callback_with_param, this, std::placeholders::_1) 1); 
//or a lambda 
menuitem->setCallBack(CC_CALLBACK_1([](Ref* sender){ }, this)); 

我需要怎麼做才能創建一個函數的回調函數,並且參數已經被填充了?

+0

如果您使用'std :: bind',請不要使用宏(正如您在問題中所顯示的,宏本身使用'std :: bind')。使用['std :: bind']的示例(http://en.cppreference.com/w/cpp/utility/functional/bind):'std :: bind(&MyClass :: my_callback_with_param,this,std :: placeholders: :_1,an_int)' –

+0

@JoachimPileborg我認爲就是這樣。把它扔在答案中。謝謝。 – TankorSmash

+0

@JoachimPileborg是的,這是絕對的。我的問題是我在測試過程中使用了一個自動變量,以節省輸入所有這些臨時變量,並且使用'CC_CALLBACK_X'創建的類型與lambdas或我一直在做的綁定不兼容。所以,關閉,但不是雪茄。你的答案只是票,再次感謝.. – TankorSmash

回答

0
menuitem->setCallback(std::bind(MyClass::my_callback_with_param, this, 1); 

方法名調用std::bind,通過this作爲第一個參數,然後你想後,任何其他。適用於無限變量。

相關問題