Reading List

The Selfish Gene
The Psychopath Test: A Journey Through the Madness Industry
Bad Science
The Feynman Lectures on Physics
The Theory of Everything: The Origin and Fate of the Universe


ifknot's favorite books »

Sunday, 13 April 2014

Static variables in template class results in smart enqueuer-dequeuer pattern.

Decorator pattern[1] tricks to reduce queue dependency


TL;DR this one simple trick for static member initialization in a class template[2].

The original rather dumb enqueuer and dequeuer used the shared_queue class to track their counts and close the underlying queue accordingly. Giving them each their own static count makes the shared_queue wrapper redundant and usage more intuitive, but how to initialise the static variable was a brief head scratcher...

Smart dequeuer decorator:

namespace que {
template<typename T>
class dequeuer final {
using value_type = typename T::value_type;
public:
dequeuer(T& q): q(q) {
count++;
}
value_type dequeue() {
return q.dequeue();
}
bool try_dequeue(value_type& item) {
return q.dequeue(item);
}
inline bool is_open() {
return q.is_open();
}
~dequeuer() {
if (!--count)
q.close();
}
private:
T& q;
static unsigned int count;
};
//this one simple trick for static member initialization in a class template
template<typename T>
unsigned int dequeuer<T>::count = 0;
}
view raw dequeuer.cpp hosted with ❤ by GitHub

References:
[1] http://en.wikipedia.org/wiki/Decorator_pattern
[2] static member initialization in a class template

No comments:

Post a Comment