C ++ Function Queue

So, I have several methods with different arguments:

class c; void c::foo1(int a) { } void c::foo2(int a, int b) { } 

How do I have a queue / vector of these functions? It does not have to be a std :: function object, but I need a way to block the execution of functions.

+6
source share
3 answers

Your question is a bit vague, but if you already know the target and the arguments to call while you are inserting the functions into the queue, you can use the queue without lambdas parameters:

 std::deque<std::function<void()>> q; cx; q.push_back( [&x] { x.foo1(1); } ); q.push_back( [&x] { x.foo2(2,3); } ); // ... some time later we might want to execute the functions in the queue ... while (!q.empty()) { q.front()(); q.pop_front(); } 
+9
source

The short answer is that you cannot. A translucent way would be to make all functions take a list or argument vector, where each argument is int, or if you need to support more argument types, Boost Variant. Then all functions can have the same signature, and their implementations will have to unpack their arguments.

If all methods are within the same class, you can save them in the list as simple pointers to member functions. This would be more efficient than storing them in std :: functions, and clearer if you succeed.

0
source

Your intention is unclear. To extend the answer to @JohnZwicnk ...

A functional signature includes its return type, its type of the class object (if it is a member function of the class), and its parameters, which means that there is no easy way to make a general "type of function".

This does not mean that you cannot assign different types of functions to the same type of objects. boost :: function and boost :: mem_function are two examples of how you can "assign" a common function with parameters to an object and walk it around before it is called.

If you intend to simply call each function sequentially without worrying about the type, look at the functors or the aforementioned boost :: mem_function. Both of these functions allow you to either bind or assign parameters to a function call and defer function evaluation for later versions.

0
source

All Articles