Tips on implementing a function queue with unique queue items (compare function problem)
Hi,
Anyone have a tip or pointer regarding how to implement a function queue
with unique items?
Comparing C++ delegates seems to be hard in general
(http://www.boost.org/doc/libs/1_39_0/doc/html/function/faq.html#id1877737)
but there are probably workarounds that are alright. It would be nice of
course if the queue user stays unaffected by the workaround but that is
probably not possible. Another layer perhaps.
Any suggestion for the code below?
class UniqueFunctionQueue
{
public:
typedef boost::function
AMDG Peter Åberg wrote:
Anyone have a tip or pointer regarding how to implement a function queue with unique items?
Comparing C++ delegates seems to be hard in general (http://www.boost.org/doc/libs/1_39_0/doc/html/function/faq.html#id1877737) but there are probably workarounds that are alright. It would be nice of course if the queue user stays unaffected by the workaround but that is probably not possible. Another layer perhaps. Any suggestion for the code below?
class UniqueFunctionQueue { public: typedef boost::function
QueueItem; public: void push(QueueItem item) { /* ToDo, would be nice to do: if (item is already in the queue) return; */ queue.push_back(item); } void execute() { for(std::deque<QueueItem>::iterator i = queue.begin(); i != queue.end(); i++) (*i)(); queue.clear(); }
private: std::deque<QueueItem> queue; };
....
UniqueFunctionQueue queue; queue.push(boost::bind(&Synchronizer::sync, &synchronizer, LeftToRight)); queue.push(boost::bind(&Synchronizer::sync, &synchronizer, RightToLeft)); queue.push(boost::bind(&Initializer::init, &initializer)); queue.push(boost::bind(&Synchronizer::sync, &synchronizer, LeftToRight)); // Should not be added since there is one in the queue already. queue.execute();
If the caller of push knows the type of the function object, then you can template the push function. template<class F> void push(const F& f) { if(std::find_if(queue.begin(), queue.end(), f == _1) != queue.end()) { queue.push_back(item); } } This is going to be pretty inefficient because of the linear search, but the same idea applies if you want to store the function objects in a data structure that supports faster lookup. In Christ, Steven Watanabe
Peter Åberg wrote:
Anyone have a tip or pointer regarding how to implement a function queue with unique items?
You're right that we can't compare two boost::function objects, but it *is* permitted to compare a boost::function with an rvalue that could initialize it. If you make your push() method a template accepting an argument of arbitrary type, presumably you could compare each existing item with that new value before storing it into the deque.
participants (3)
-
Nat Goodspeed
-
Peter Åberg
-
Steven Watanabe