Game Development Reference
In-Depth Information
handler += [](void*, int data)
{ std::cout << “Callback: “ << data << std::endl; }
When the event is invoked by calling
handler.Invoke(this, n);
(where n is any int), the
lambda function will be called and we would see the output “Callback: n” in the standard
output.
It's possible to use
std::function
in conjunction with
std::bind
, which allows us to create
functions for which certain arguments are already bound to some value to bind a function
object to a member function of an object.
using std::placeholders;
event_handler<wchar_t> inputEventHandler;
keyboard keyb;
auto onInputFunction =
std::bind(&keyboard::OnInput, &keyb, _1, _2);
inputEventHandler += onInputFunction;
In this example, we know that an event handler expects a callback function with the signa-
ture (void*, T), where T is defined by the template argument, these parameters are repres-
entedbytheplaceholder values_1,_2and
std::bind
returnsafunctionpointertothe
OnIn-
put
member function in the object keyb. This is one possible use of
std::bind
, however it
can also be used for argument reordering, binding to member data as well as functions and
of course, creating functions with bound arguments.
Static functions may also be provided as callbacks:
static void onEvent(void* sender, int d)
{
std::cout << “Callback: “ << data << std::endl;
}
event_hander<int> handler;
handler += onEvent;
In short, it's possible to bind any callable object to an event handler, which one you choose
will depend entirely on the game's code architecture or a particular feature.