boost - How to get a general function pointer as a private member of a C++ class? -
in game i'm making, there triggers. when trigger collides anything, happen; if door trigger, player moved new area. if it's explosion trigger, , explosion happens. chair trigger may make player sit down.
i don't want subclass each , every trigger. each 1 shares enough important info, , each activate using common interface. difference between them routine called on collision.
the problem functions may have differing signatures.
for example, move player function requires few things.
void move_player(environment *new_env, player *player, int new_x, int new_y)
but explosion trigger may be
void explode()
i need class accepts move_player
, explode
.
here's think pseudo code should like
class trigger { public: trigger(function_pointer f) { fp = f; } void activate() { fp(); } private: func_pointer fp; }
i thinking initializing/using this.
auto f = std::bind(move_player, new_environment, my_player, 0, 0); trigger tigger (f); tigger.activate();
i've tried going std documentation , searching around other forums, along checking out boost documentation. know how use bind, , i'm pretty sure should work here, have no how set function pointer within class of 1 indifferent argument lists. minimum working example awesome.
you use std::function
in combination std::bind
, variadic templates example below:
class trigger { std::function<void()> fp; public: template<typename f, typename ...args> trigger(f f, args... args) : fp(std::bind(f, args...)) { } void activate() { fp(); } };
Comments
Post a Comment