I’m more of a hardware person, but the chip design tools I’m using require me to write some C++ code. I am not familiar with object-oriented programming; although I have a good handle on C. What I’m asking is for an explanation of how to structure my class (called cq) to accomplish the task at hand.
I would like to be able to generate a queue of a specified data type and specified size (which should not change after being generated). Ideally, this would be accomplished like this…
my_queue = new cq(uint8_t, 6);
…which would generate an array (or vector) of six 8-bit unsigned integers.
Then, I would like a method to both insert an element to an end and return the element at the head of the queue as follows.
uint8_t front;
front = my_queue.advance(28);
What kind of structure do I need to accomplish this? Do I need a template since the data types are variable? Or should I have a generic class and have a class for each data type inherit its structure?
Thank you!
Edit: using input from the answers below, I’ve come up with the following:
template <class type>
template <class size>
class CQ {
private:
// Allocates a queue with type and size
// specified by template arguments.
std::queue<type> cycle_queue(size, 0);
public:
// Inserts input to the end of the queue;
// removes and returns the front element.
type advance(type in){
type out = cycle_queue.front();
cycle_queue.push_back(in);
cycle_queue.pop_front();
return out;
}
}
My question then becomes… how do I instantiate this in my main C++ program? I tried this, but it did not work:
CQ<uint8_t><6> my_queue;
my_queue.advance(28);
Thanks again!
This looks like a perfect application for STL containers. You could write your own queue class (as a template class, since you want to be able to specify data type), but why re-invent the wheel?
You’re looking probably for:
std::list, for a FIFO queue. For your particular example:If you’re not already somewhat familiar with OOP and C++, writing your own template classes might be a bit out of reach for now. There are good references all over the ‘net though if you want to try: e.g. http://www.cplusplus.com/doc/tutorial/templates/