| |
21.2.7.Queue buffer |
|
#include <queue>
#include <stdexcept>
#include <iostream>
using namespace std;
using std::queue;
template <typename T>
class PacketBuffer{
public:
PacketBuffer(int maxSize = -1);
void bufferPacket(const T& packet);
T getNextPacket() throw (std::out_of_range);
protected:
queue<T> mPackets;
int mMaxSize;
private:
PacketBuffer(const PacketBuffer& src);
PacketBuffer& operator=(const PacketBuffer& rhs);
};
template <typename T>
PacketBuffer<T>::PacketBuffer(int maxSize)
{
mMaxSize = maxSize;
}
template <typename T>
void PacketBuffer<T>::bufferPacket(const T& packet)
{
if (mMaxSize > 0 && mPackets.size() == static_cast<size_t>(mMaxSize)) {
return;
}
mPackets.push(packet);
}
template <typename T>
T PacketBuffer<T>::getNextPacket() throw (std::out_of_range)
{
if (mPackets.empty()) {
throw (std::out_of_range("Buffer is empty"));
}
// retrieve the head element
T temp = mPackets.front();
// pop the head element
mPackets.pop();
// return the head element
return (temp);
}
class IPPacket {};
int main(int argc, char** argv)
{
PacketBuffer<IPPacket> ipPackets(3);
ipPackets.bufferPacket(IPPacket());
ipPackets.bufferPacket(IPPacket());
ipPackets.bufferPacket(IPPacket());
ipPackets.bufferPacket(IPPacket());
while (true) {
try {
IPPacket packet = ipPackets.getNextPacket();
} catch (out_of_range&) {
cout << "Processed all packets!" << endl;
break;
}
}
return (0);
}
|
|
|