Skip to content

Instantly share code, notes, and snippets.

@Justasic
Created June 4, 2013 19:54
Show Gist options
  • Save Justasic/5709013 to your computer and use it in GitHub Desktop.
Save Justasic/5709013 to your computer and use it in GitHub Desktop.
Use C++11 features to implement a function queue which calls functions later but queues them up in a FIFO queue. Compile with: clang -std=c++11 -stdlib=libc++
#include <iostream>
#include <functional>
#include <queue>
// These includes are for later experimentation
#include <thread>
#include <atomic>
std::queue<std::function<void()>> funcs;
template<typename _Callable, typename... _Args>
void QueueFunction(_Callable&& __f, _Args&&... __args)
{
std::function<void()> func = std::bind(std::forward<_Callable>(__f), std::forward<_Args>(__args)...);
funcs.push(func);
}
void CallFuncs()
{
while(!funcs.empty())
{
std::function<void()> func = funcs.front();
funcs.pop();
func();
}
}
void print_things(const std::string str)
{
std::cout << str << std::endl;
}
int main()
{
std::string str("Hello");
QueueFunction(print_things, str);
CallFuncs();
return 0;
}
@crearo
Copy link

crearo commented Oct 14, 2019

This is great but this won't work for member functions. Any idea how I could get that to work?

@crearo
Copy link

crearo commented Oct 14, 2019

I used a queue of lambdas. That worked great!

@Justasic
Copy link
Author

You have to provide the first argument as a pointer to the class itself as shown in std::bind.

@okaninho
Copy link

how you have solved it to use it for member functions, please? thanks

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment