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(); } }; 

live demo


Comments

Popular posts from this blog

powershell Start-Process exit code -1073741502 when used with Credential from a windows service environment -

twig - Using Twigbridge in a Laravel 5.1 Package -

c# - LINQ join Entities from HashSet's, Join vs Dictionary vs HashSet performance -