How to write a function template that can take a stack or a queue?

I implement four algorithms that are completely identical, except for the data structure that they use - two use priority_queue, one uses stack, and the last uses queue. They are relatively long, so I would like to have only one function template that takes the container type as the template argument, and then each algorithm calls this template with the corresponding argument, for example:

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 */);
}

priority_queue - stack, queue, (front( ) top( )). , , ( ).

? - , top( ), stack, , STL - -. ?

+5
5

non-member top, :

template <typename T>
T& top(std::stack<T>& s) { return s.top(); }

template <typename T>
T& top(std::queue<T>& q) { return q.front(); }

// etc.

( Sequence), , .

(, std::vector), .

+7

:

template<class Container>
struct foo_detail {
  static typename Container::value_type& top(Container &c) { return c.top(); }
  static typename Container::value_type const& top(Container const &c) { return c.top(); }
};
template<class T, class Underlying>
struct foo_detail<std::queue<T, Underlying> > {
  typedef std::queue<T, Underlying> Container;
  static typename Container::value_type& top(Container &c) { return c.front(); }
  static typename Container::value_type const& top(Container const &c) { return c.front(); }
};

template<class Container>
void foo(/* args */)
{
    Container dataStructure;
    // Use foo_detail<Container>::top(dataStructure) instead of dataStructure.top().
    // Yes, I know it ugly.  :(
}
+2

std::queue ; , , queue, queue. :

template <typename QueueType>
class QueueWrapper {
public:
    explicit QueueWrapper(const QueueType& q) : queue(q) {
        // Handled in initializer list
    }

    typedef typename QueueType::value_type value_type;

    value_type& top() {
        return queue.front();
    }
    const value_type& top() const {
        return queue.front();
    }

    void pop() {
        queue.pop();
    }
private:
    QueueType queue;
};

, !

+1

queue, priority_queue stack - ; ( deque queue stack vector priority_queue).

vector, deque list ( "" ) , .

, STL; (, , , ).

0

front() top() , STL *begin().

-1

All Articles