I have written the following wrapper for std::bind and std::queue:
#include "Queue.h"
template<class T>
Queue<T>::Queue(T* input)
{
instance = input;
}
template<class T> template<typename... Args>
int Queue<T>::push(int (T::*func)(Args... args), Args... args)
{
queue.push(std::bind(func, instance, args...));
return queue.size();
}
template<class T>
int Queue<T>::pop()
{
if(!queue.empty())
{
queue.front()();
queue.pop();
return queue.size();
}
return 0;
}
template<class T>
bool Queue<T>::empty()
{
return queue.empty();
}
template<class T>
size_t Queue<T>::size()
{
return queue.size();
}
with the following header:
#ifndef QUEUE_H_
#define QUEUE_H_
#include <functional>
#include <queue>
template <class T>
class Queue
{
private:
std::queue<std::function<void()>> queue; /**< the messaging queue, appended to using enqueue(), popped from using dequeue() */
T* instance;
public:
Queue(T*);
template<typename... Args>
int enqueue(int (T::*f)(Args... args), Args... args);
int dequeue();
bool empty();
size_t size();
};
#endif
It allows me to add bound function expressions to a queue and pop them afterwards (queue->push<int>(&Object::jumpAround, 10); and queue->pop()). The problem is, I could not find a generic object- and function-pointer that enabled me to implement this without the <class T> template.
I know that using templates would probably be the safest and best approach here but due to the design of the code implementing this queue I need to get rid of it. Any ideas?
I guess it must be possible somehow because std::bind‘s first parameter can be any function and the second one can be any Object.
If I understand, below is what you require:
Oh and how to use it:
Should output:
Or, even better, change your function signature and allow users to enqueue a
std::function! This is the “normal” way (see for example,boost::asio::io_service::post.)EDIT: Here is a simple example:
Now to post any function to this queue…