Boost bind and boost function, storing functions with arguments in a vector, and then executing them

Sorry for the poorly spelled title.

I looked through the documentation, but I can not find anything that could solve this problem.

Basically, I want to save a few function1<void, void*> with the provided arguments in a vector, and then execute them at a later stage.

This is what I want to accomplish:

 typedef boost::function1<void, void*> Task; Vector<Task> mScheduledTasks; int MyArg = 5; void SomeTask(void* arg) { // .... } void AddSomeTasks() { // nevermind that MyArg is globally accessible for (int i = 0; i<5; i++) mScheduledTasks.push_back(boost::bind(&SomeTask, _1), (void*)&MyArg); } void ExecuteTask() { Task task = mScheduledTasks.front(); task(); } 

Now executing task () requires me to pass an argument, but I pass it to AddSomeTasks? Why is this not used? Or did I skip using boost :: bind?

thanks

+4
source share
2 answers

your Task type requires an argument, it must be boost::function0<void> . When you bind an argument, the returned (bound) called object has arity 0, not 1.

Also, to bind the argument that you pass to it by calling boost::bind , _1 , etc. for arguments that remain unrelated, not what you want here.

Something like (untested):

 typedef boost::function0<void> Task; Vector<Task> mScheduledTasks; int MyArg = 5; void SomeTask(void* arg) { // .... } void AddSomeTasks() { // nevermind that MyArg is globally accessible for (int i = 0; i<5; i++) mScheduledTasks.push_back(boost::bind(&SomeTask, (void*)&MyArg)); } void ExecuteTask() { Task task = mScheduledTasks.front(); task(); } 
+4
source

It depends on when you want to pass the argument. The push_back call mixes up two different concepts. It is not clear from the message whether you want to pass MyArgs during the bind call, in which case you will return a function object that takes no arguments and returns void if you want to pass MyArgs during the execution of the task. For the first, as @ForEveR said, the right call

 mScheduledTasks.push_back(boost::bind(&SomeTask, (void*)&MyArg)); 

and you need to change your typedef for Task so that it doesn't accept any arguments. If you want to pass an argument at the call point of the Task object, then the push_back call will look like this:

 mScheduledTasks.push_back(boost::bind(&SomeTask, _1)); 

This will create a function object with a function call operator that takes one argument and returns void. Then you change the call to task() in ExecuteTask to pass any argument you have.

+3
source

Source: https://habr.com/ru/post/1433046/


All Articles