Created
June 4, 2013 19:54
-
-
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++
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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; | |
} |
I used a queue of lambdas. That worked great!
You have to provide the first argument as a pointer to the class itself as shown in std::bind.
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
This is great but this won't work for member functions. Any idea how I could get that to work?