c++ - function array with functions from different objects -


i don't have experience using array of functions in c++. need use array of functions array contains functions different objects. here dummy code illustrate want implement.

class base_class { public:   virtual int function1(int arg1, int arg2);   virtual int function2(int arg1, int arg2); };  class derived_class : public base_class { public:   int function1(int arg1, int arg2) { /* ... */ };   int function2(int arg1, int arg2) { /* ... */ };   // ... };  typedef int (*functions) (int arg1, int arg2);   int main() {   derived_class object1;     derived_class object2;      functions func_instance[4];   func_instance[0] = object1.function1;   func_instance[1] = object1.function2;   func_instance[2] = object2.function1;   func_instance[3] = object2.function2;   // ... } 

i can't work, throws following error:

error: argument of type int () (int , int) not match int (*) (int, int) 

the easiest way use std::function , std::bind.

#include <functional> #include <array>  derived_class object1; derived_class object2;  std::array< std::function<int(int, int)>, 2> >    arr = {{ std::bind(&derived_class::function1, &object1)          , std::bind(&derived_class::function2, &object1)}};          // , on 

note object1 , object2 have been bound address. need keep them alive long bound functions alive. if write object1 in bind expression copy of object stored in bound function , no scope problems occur.

c++03 complete example hand-rolled, single-purpose binder-type:

#include <iostream>  struct base {   virtual void f0() { std::cout << "f0 base" << std::endl; }   virtual void f1() { std::cout << "f1 base" << std::endl; } };  struct derived : base {   void f0() { std::cout << "f0 derived" << std::endl; }   void f1() { std::cout << "f1 derived" << std::endl; } };  // typedef pointer member function  // of base accepts arguments , returns void typedef void (base::*memberptrtype)(void);  // pack pointer class , pointer member function struct binder {   memberptrtype ptr;   base*         base;    // shortcut call thing, might want    // have overload of operator() , result_type typedef   void call()   { ((base)->*(ptr))(); } };   int main() {   base b;   derived d;    // initialize 4 element array of binder, first argument function,   // second object call on   //    // remember b , d need alive long    // want call in array   binder arr[4] = { {&base::f0, &b}, {&base::f1, &b},                      {&base::f0, &d}, {&base::f1, &d}};    // walk through array , call each   for(binder* begin = arr; begin != arr + 4; ++begin)   {     begin->call();   }     return 0; } 

Comments

Popular posts from this blog

c# - DetailsView in ASP.Net - How to add another column on the side/add a control in each row? -

javascript - firefox memory leak -

Trying to import CSV file to a SQL Server database using asp.net and c# - can't find what I'm missing -