Pointer to save function + arguments for later use

I have this problem when a pointer to a C ++ function is stored along with a set of arguments to call it so that it can be called later. The calling code does not know the type and arguments of the functions. Saving and calling function pointers and arguments is extremely critical in my application. The interface should look something like this:

void func( int a, char * b );
call_this_later( func, 5, "abc" );

A simple solution is to put all this information in a functor, requiring a different typedef for each function being called. C ++ 11 would allow me to do this using a variational pattern, so that's fine.

Since the type of functor is unknown at the point of call, it seems necessary to create a virtual base class for these functors and call functors using virtual function calls. The overhead of virtual functions + heap allocation is too high (I push the boundaries of the implementation of this idiom with minimal assembly instructions). So I need a different solution.

Any ideas?

+5
source share
3 answers

How about a solution using boost :: function / boost :: binding :

void func( int a, char * b );

boost::function<void ()> my_proc = 
    boost::bind(&func, 5, "abc");

// then later...

my_proc(); // calls func(5, "abc");
+3
source

You can do this with a lambda expression that captures types.

template <typename Func, typename Arg1, typename Arg2>
std::function<void(void)> call_this_later(Func f, Arg1 a1, Arg2 a2) {
    return [=]() { f(a1, a2); }; // Capture arguments by value
}

A few notes:

  • , ,
  • ++ , , , . , const char*, , , someStdString.c_str(), .
  • , , , .
+2

. , .

0
source

All Articles