1

I'm currently going from C# to C++ and rewriting some game engine code and I think I'm at a wall with tr1; Essentially what I want to do is have an input layer take input from the touchscreen and then fire a callback to notify any elements listening to that input. Now tr1/boost seem to make this super easy via the use of function and bind, however firing callbacks that are void() is no problem, but now I'm trying to send parameters through to these callback when invoke (enums for instance).

The problem here is that when I call bind, and insert the parameter, it doesn't act as a place holder rather it acts as the permanent value to be passed. For instance my code here:

Containing class:

tr1::function<void (MenuActions action)> callback;
callback = tr1::bind(&MenuScene::handleInputCallback, this, MenuActions::neutral);
m_menuUILayer->registerCallback(callback);

Has the intent that I create a function and bind it then registerCallback passes this callback into the member class and stores the reference. This part works, but now in the member class I can invoke the callback however the default parameters are always sent...

Member class:

if (m_callback)
{
    m_callback(MenuActions::backgroundTouchDown);
}

So here rather than MenuActions::backgroundTouchDown being sent to the main containing class in the callback, the default MenuActions::neutral is still being used. I'm wondering if I'm missing something, or perhaps my lack of sleep is just sending me down the wrong path? Thanks guys!

JedH
  • 124
  • 7

1 Answers1

5

You should use placeholders

callback = tr1::bind(&MenuScene::handleInputCallback, this,
tr1::placeholders::_1);

and then call like

if (m_callback)
{
    m_callback(MenuActions::backgroundTouchDown);
}

and your function handleInputCallback can have default parameter, defaulted to MenuActions::neutral

ForEveR
  • 55,233
  • 2
  • 119
  • 133
  • 1
    The namespace is `std::tr1::placeholders`. – juanchopanza Mar 11 '13 at 06:57
  • It should be noted that `function` and `bind` have made it to C++11 standard and are now `std::function`, `std::bind` and `std::placeholders::_`n. – Jan Hudec Mar 11 '13 at 07:02
  • Thanks guys this was exactly what I needed! Two questions to elaborate on your answers and comments: 1) Is it safe to use std over tr1 now if I'm doing cross platform development (Windows Phone, Win8, Android, iOS)? **2)** @ForEveR , do you mind elaborating on what's going on when you pass _1? Is this just a flag that tells tr1 to ignore a default? I'm curious as I will likely be implementing function with **placeholder** in there a lot more now and would like to know what's going on. Thanks again! – JedH Mar 11 '13 at 07:23