简体   繁体   中英

How to make a class capable of calling array of other classes functions?

What we need is a class with 2 methods add() and call(). When we create a class we can add using add() function a function we want to be called when call() will be called with params like (pseudocode)

new A;
new B;
A.add(B.function(int)) // B takes int as an argument
A.call(); // and call() would look like {int i; sendArrayOfSubscribers(i);}
//now we know that B.function was executed with param generated in A;

Is such a structure possible in C++?

Your code is very unclear but it appears you want to set up an array of tasks then perform them all.

You can use boost::function to create each function and you can have a collection (vector) of them.

Then invoke each function. Something like:

typedef boost::function< void (void) > func_type;
std::vector< func_type > funcs;
// populate funcs, 
std::for_each( funcs.begin(), funcs.end(), boost::bind(&func_type::operator(),_1) );

should work. (There may be a simpler construct)

You use more boost::binds to create your collection "funcs". The functions do not have to take no parameters, they can take "int" like you required. You pass that in when you bind, eg:

funcs.push_back( boost::bind( &B::function, b, i ) );

where "b" is an instance of b and i is the parameter it takes as an int.

Try this (I had to rename do , it's a keyword in C++):

#include <iostream>
#include <vector>

using namespace std ;

typedef void FuncInt (int) ;

class A {
public:
  void add (FuncInt* f) ;
  void call() ;  
private:
  vector<FuncInt*> FuncVec ;
} ;

void A::add (FuncInt* f) {
  FuncVec.push_back (f) ;
}

void A::call() {
  for (size_t i = 0 ; i < FuncVec.size() ; i++)
    FuncVec[i] (i) ;
}

static void f0 (int i) { cout << "f0(" << i << ")" << endl ; }
static void f1 (int i) { cout << "f1(" << i << ")" << endl ; }

int main() {
  A a ;
  a.add (f0) ;
  a.add (f1) ;
  a.call() ;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM