I'm implementing four algorithms that are completely identical except for what data structure they use — two use priority_queue
, one uses stack
, and the last uses queue
. They're relatively long, so I'd like to have just one function template that accepts the container type as a template argument and then have each algorithm call that template with the appropriate argument, like so:
template <class Container>
void foo(/* args */)
{
Container dataStructure;
// Algorithm goes here
}
void queueBased(/* args */)
{
foo<queue<Item> >(/* args */);
}
void stackBased(/* args */)
{
foo<stack<Item> >(/* args */);
}
I've managed to do just this with the priority_queue
- and stack
-based implementations, but I can't do the same for the queue
-based algorithm because it uses a different name to access the foremost element (front( )
instead of top( )
). I know that I could specialize the template for this case, but then I'd have a big stretch of duplicated code (which is what I'm trying to avoid).
What's the best way to accomplish this? My first instinct was to create a wrapper class for queue that adds a top( )
operation equivalent to stack
's, but I've been reading that subclassing STL classes is a no-no. How should I get this behavior, then?