I am trying to construct a class that is essentially a queue of futures that are all handled asynchronously and eventually all stored when main wants to get their values. I am having trouble creating the function parameters that will accept these functions and their arguments in order to create an async operation that is then pushed in to the queue of futures. The areas in question are the call constructor and the member function add(). Here is what I have so far:
#include <iostream>
#include <queue>
#include <future>
#include <thread>
using namespace std;
using longInt = unsigned long long int;
//prototypes
longInt isPrime(longInt);
template <typename return_type>
class TaskQueue {
private:
queue<future<return_type>> tasks;
public:
//return a copy of the queue
queue<future<return_type>> copy() const {
return tasks;
}
//default constructor
//does nothing, waits for input
TaskQueue() {
//do nothing
}
//call constructors
//adds task to queue
TaskQueue(return_type (*func)(), Args&& ... args) {
tasks.push(new async(func, args));
}
//copy constructor
//copies another queue to this one
TaskQueue(const queue<future<return_type>> & in) {
tasks = in.copy();
}
//setter and getter functions
//inserts a new task into the queue
void add(return_type(*func)(), Args&& ... args) {
tasks.push(new aync(in, args));
}
//returns true if the task at the top of the queue is ready
bool valid() {
return tasks.front().valid();
}
//gets the value, if the value is not ready, waits for it to be ready
//pops the top task after getting it
return_type get() {
return_type temp = tasks.top().get();
tasks.pop();
return temp;
}
//waits for the value of the top of the queue to become ready
void wait() {
tasks.top().wait();
}
};
int main() {
TaskQueue<longInt> checkPrimes;
checkPrimes.add(isPrime, 5);
longInt test = checkPrimes.get();
cout << test << endl;
}
//returns the number if it is prime or 0 if it is not
longInt isPrime(longInt n) {
if (n <= 3) {
if (n > 1) {
return n;
}
return 0;
}
if (n % 2 == 0 || n % 3 == 0) {
return 0;
}
for (unsigned short i = 5; i * i <= n; i += 6) {
if (n % i == 0 || n % (i + 2) == 0) {
return 0;
}
}
return n;
}
A compilable version:
template <typename return_type>
class TaskQueue {
private:
queue<future<return_type>> tasks;
public:
//return a copy of the queue
queue<future<return_type>> copy() const {
return tasks;
}
//default constructor
//does nothing, waits for input
TaskQueue() {
//do nothing
}
//call constructors
//adds task to queue
template <typename ... Args, typename ... Ts>
TaskQueue(return_type (*func)(Ts...), Args&& ... args) {
tasks.push(std::async(func, args...));
}
//copy constructor
//copies another queue to this one
TaskQueue(const queue<future<return_type>> & in) {
tasks = in.copy();
}
//setter and getter functions
//inserts a new task into the queue
template <typename ... Args, typename ... Ts>
void add(return_type(*func)(Ts...), Args&& ... args) {
tasks.push(std::async(func, args...));
}
//returns true if the task at the top of the queue is ready
bool valid() {
return tasks.front().valid();
}
//gets the value, if the value is not ready, waits for it to be ready
//pops the top task after getting it
return_type get() {
return_type temp = tasks.front().get();
tasks.pop();
return temp;
}
//waits for the value of the top of the queue to become ready
void wait() {
tasks.top().wait();
}
};
Demo
I think you can define a type for the function you want to pass and then apply them in the order you want. For example, the following snippet will define a intfunc type, which is a function that takes an int and returns an int.
typedef int (*intfunc) (int);
We can then define functions like
int sum2(int n) {
return n + 2;
}
int mult3(int n) {
return 3 * n;
}
and give them to a vector,
vector<intfunc> funcs;
vector<intfunc>::iterator func;
int start = 0;
funcs.push_back(sum2);
funcs.push_back(mult3);
cin >> start;
for (func = funcs.begin(); func != funcs.end(); ++func)
{
start = (*func)(start);
}
cout << start << endl;
If we enter 5 to that program, it will return 21 as expected.
Related
Using a producer-consumer pattern I'd like to submit calls to the member functions of struct A i.e., func_1() and func_2() by passing the name of the function object (something like A::func_1), and a list of arguments taken by these functions in a queue-like buffer queue_in. I'd then like to collect these results (here a std::variant of all the possible return types (double and int)) in another buffer queue_out for later processing.
At the moment, I'm only able to hack my way by having q_in hold std::string and enumerating all the possibilities manually. Of course I'm also missing passing any possible arguments to func_1() and func_2().
#include <iostream>
#include "blockingconcurrentqueue.h" // https://github.com/cameron314/concurrentqueue
#include <variant>
using Result = std::variant<double, int>;
using queue_in = moodycamel::BlockingConcurrentQueue<std::string>;
using queue_out = moodycamel::BlockingConcurrentQueue<Result>;
struct A {
explicit A(queue_in &q_in, queue_out &q_out) {
std::thread t([&]() {
for (;;) {
std::string s;
if (q_in.wait_dequeue_timed(s, -1)) {
if (s == "1")
q_out.enqueue(this->func_1());
else if (s == "2")
q_out.enqueue(this->func_2());
}
std::this_thread::sleep_for(std::chrono::seconds(1));
}
});
t.join();
}
double func_1() const { // func_1 might have arguments!
std::cout << "func_1() called.\n";
return 13.0f;
}
int func_2() const { // func_2 might have arguments!
std::cout << "func_2() called.\n";
return 1;
}
};
void producer(queue_in &q_in, const size_t N) {
for (size_t i = 0; i != N; ++i) {
q_in.enqueue("1" /*..., arguments for func_1*/); // prefer to call the function-object instead
q_in.enqueue("2" /*..., arguments for func_2*/);
}
}
void result_consumer(queue_out &q_out) {
for (;;) {
Result r;
if (q_out.wait_dequeue_timed(r, -1)) {
std::visit([](auto &&arg) {
std::cout << "The result is: " << arg << std::endl;
}, r);
}
std::this_thread::sleep_for(std::chrono::seconds(0));
}
}
int main() {
const size_t N = 2;
queue_in q_in;
queue_out q_out;
std::thread producer_thread(producer, std::ref(q_in), N);
std::thread result_consumer_thread(result_consumer, std::ref(q_out));
A a(q_in, q_out);
producer_thread.join();
result_consumer_thread.join();
}
How can I do this instead via function objects? Second, how do I invoke any possible arguments for the member functions of A. And third, can I avoid the use of a std::variant like result type?
Taking inspiration from #n.1.8e9-where's-my-sharem. 's comments here's how I got the above to work using std::function and std::bind
using Result = std::variant<double, int>;
using FO = std::function<Result(void)>;
using queue_in = moodycamel::BlockingConcurrentQueue<FO>;
using queue_out = moodycamel::BlockingConcurrentQueue<Result>;
struct A {
explicit A(queue_in &q_in, queue_out &q_out) {
std::thread t([&]() {
for (;;) {
FO o;
if (q_in.wait_dequeue_timed(o, -1)) {
q_out.enqueue(o());
}
std::this_thread::sleep_for(std::chrono::seconds(1));
}
});
t.detach();
}
void consumer() {
}
double func_1(double x, const size_t &s) const { // note the arguments
std::cout << "func_1() called.\n";
return x + s;
}
int func_2(int x) const {
std::cout << "func_2() called.\n";
return x;
}
};
void producer(const A& a, queue_in &q_in, const size_t N) { // note the first argument: the producer() must know about some instance of A
for (size_t i = 0; i != N; ++i) {
FO o;
if (i % 2 == 0)
o = std::bind(&A::func_1, a, double(i), size_t(10));
else
o = std::bind(&A::func_2, a, int(i));
q_in.enqueue(o);
}
}
void result_consumer(queue_out &q_out) {
for (;;) {
Result r;
if (q_out.wait_dequeue_timed(r, -1)) {
std::visit([&](auto &&arg) {
std::cout << "The result is: " << arg << std::endl;
}, r);
}
std::this_thread::sleep_for(std::chrono::seconds(1));
}
}
int main() {
const size_t N = 2;
queue_in q_in;
queue_out q_out;
A a(q_in, q_out);
std::thread producer_thread(producer, std::ref(a), std::ref(q_in), N);
std::thread result_consumer_thread(result_consumer, std::ref(q_out));
producer_thread.join();
result_consumer_thread.join();
}
Output:
func_1() called.
The result is: 10
func_2() called.
The result is: 1
hi I am using make_heap in my cpp program. I have written below code corresponding to it-
struct jobs {
int abs_deadline, id, rem_ET, arr_time;
};
struct compareDeadline {
bool comparator(jobs t1, jobs t2) {
return t1.abs_deadline < t2.abs_deadline;
}
};
struct compareArrTime {
bool comparator( jobs t1, jobs t2) {
return t1.arr_time < t2.arr_time;
}
};
void runningPhase(int ntasks,vector<tasks> j) {
vector<jobs> ready_queue,waiting_queue;
int system_criticality = 1, temp, timer = j[0].arr_time;
cout << "\nSCHEDULE:\n\n";
for (int i = 1; i <ntasks; i++) {
if (j[i].criticality == 1) {
temp = j[i].arr_time + j[i].deadline;
if (timer == j[i].arr_time) {
ready_queue.push_back({ temp,j[i].id, j[i].wcet[0],j[i].arr_time });
}
else {
waiting_queue.push_back({ temp,j[i].id,j[i].wcet[0],j[i].arr_time });
}
}
}
make_heap(ready_queue.begin(), ready_queue.end(), compareArrTime());
make_heap(waiting_queue.begin(), waiting_queue.end(), compareDeadline());
schedule(j, ready_queue, waiting_queue,ntasks);
}
Getting attached error
error
Any help will be apreciated.
You are passing an argument of type compareArrTime to make_heap. That's fine.
Let's call it cat. Inside make_heap, it will try to call it thus: cat(one, two).
But your compareArrTime doesn't have an operator () defined.
Hence the error.
You should write it thus:
struct compareArrTime {
bool operator ()( jobs t1, jobs t2) const {
return t1.arr_time < t2.arr_time;
}
};
and probably take t1 and t2 by const & rather than by value.
I have a producer-consumer queue which is being updated by parallel programs. The queue is queried for various statistics like mean or standard deviation or variance or something else on the current queue contents. For mean, this is the code, I use
class BufferQueue {
const int nMaxQueueSize_;
int* values;
int head, tail;
double sum;
::utils::FastMutex queue_mutex;
public:
BufferQueue(const int nMaxQueueSize) :
nMaxQueueSize_(nMaxQueueSize) {
head = tail = 0;
sum = 0;
values = new int[nMaxQueueSize_];
}
void enqueue(int val) {
values[head] = val;
if ((head + 1) % nMaxQueueSize_ == tail) {
queue_mutex.lock();
sum = val.value_point - values[tail].value_point;
utils::memory_barrier();
head = (1 + head) % nMaxQueueSize_;
tail = (1 + tail) % nMaxQueueSize_;
queue_mutex.unlock();
} else {
queue_mutex.lock();
sum += val.value_point;
utils::memory_barrier();
head = (1 + head) % nMaxQueueSize_;
queue_mutex.unlock();
}
}
bool dequeue() {
if (head != tail) {
queue_mutex.lock();
sum -= values[tail].value_point;
utils::memory_barrier();
tail = (1 + tail) % nMaxQueueSize_;
queue_mutex.unlock();
return true;
} else {
sum = 0;
return false;
}
}
MarketSpreadPoint& operator[](int i) {
return values[ (tail + i) % nMaxQueueSize_ ];
}
inline int getSize() {
return (head - tail + nMaxQueueSize_) % nMaxQueueSize_;
}
inline double average() {
queue_mutex.lock();
double result = sum / getSize();
queue_mutex.unlock();
return result;
}
~BufferQueue() {
delete values;
}
};
NOTE: One important thing to remember is that only one operation is being performed. Neither do I want to repeat code by writing separate implementations like BufferQueueAverage, BufferQueueVariance etc. I want very limit code redundancy(compiler optimizations). Even conditioning on type of queue for every update seems sub-optimal.
inline double average() {
queue_mutex.lock();
if(type_is_average){
double result = sum / getSize();
}else if(type_is_variance){
/// update accordingly.
}
double result = sum / getSize();
queue_mutex.unlock();
return result;
}
What can be a good alternative to this idea ?
Note: In this implementation, if queue is full, head automatically make the tail to move forward. In other words, the oldest element is deleted automatically.
Thanks
So you want to separate the queue from the statistics. I see two possible solutions:
Use a pattern like Template Method or Strategy to factor out the dependency.
Use a template that does this.
Assuming that all statistics you gather can gathered incrementally, the latter could look similar to the following (just meant as pseudo code):
class StatisticsMean
{
private:
int n = 0;
double mean = 0.0;
public:
void addSample(int s) { ++n; mean += (s - mean) / n; }
void removeSample(int s) { ... }
double getStatistic() const { return mean; }
}
template <typename TStatistics>
class BufferQueue
{
TStatistics statistics;
...
void enqueue(int val)
{
...
statistics.addSample(val);
}
...
double getStatistic() const { return statistics.getStatistic(); }
}
The template approach gives you full compile-time optimization. You can achieve the same with the Template Method pattern. This would also allow you to have distinct names for the getters (getStatistic() in the above example).
This could look similar to this:
class AbstractBufferQueue
{
virtual void addSample(int s) = 0;
virtual void removeSample(int s) = 0;
void enqueue(int val)
{
...
addSample(val);
}
}
class BufferQueueAverage : public AbstractBufferQueue
{
int n;
double mean;
void addSample(int s) { ++n; mean += (s - mean) / n; }
void removeSample(int s) { ... }
double getAverage() const { return mean; }
}
One way to do what you're asking is by using template classes.
First, decide on a common interface that an accumulator will have. It might be something like:
class accumulator
{
public:
typedef double value_type;
public:
void push(int v); // Called when pushing a new value.
void pop(int v); // Called when popping a new value;
value_type result(size_t n) const; // Returns the current accumulation.
};
As a special case, mean_accumulator could be this:
class mean_accumulator
{
public:
typedef double value_type;
public:
mean_accumulator() : m_sum{0} {}
void push(int v) { m_sum += v; }
void pop(int v); { m_sum -= v; }
double result(size_t n) const { return m_sum / n; };
private:
int m_sum;
};
Now, parameterize your queue by Accumulator, and call it when necessary (while you're at it, note that boost::circular_buffer has much of what you need for the implementation:
template<class Accumulator>
class queue
{
private:
boost::circular_buffer<int> m_buf;
std::mutex m_m;
public:
void push(int v)
{
// Lock the mutex, push to the circular buffer, and the accumulator
}
bool pop()
{
// Lock the mutex; if relevant, update the accumulator and pop the circular buffer
}
typename Accumulator::value_type result() const
{
// Lock the mutex and return the accumulator's result.
}
};
I'm looking for an efficient way to check if a POD variable is altered between two cycles. I've come up with this solution:
class Foo {
public:
template<typename T>
bool isChanged(T& entry);
void endCycle();
private:
std::map<void*,size_t> entryMap; // <Address orig.,Size>
std::map<void*,void*>oldVals; // <Address orig., Address cpy.>
};
template<typename T> bool Foo::isChanged(T& entry)
{
entryMap[&entry] = sizeof(T);
if(oldVals[&entry] == NULL)
return false;
if(memcmp(&entry, oldVals[&entry], entryMap[&entry]))
return true;
else
return false;
}
void Foo::endCycle()
{
// Copy all the bytes to save them for the next cycle
for( std::map<void*,size_t>::iterator entryIt = entryMap.begin();
entryIt != entryMap.end();
++entryIt)
{
if(oldVals[entryIt->first] == NULL)
oldVals[entryIt->first] = malloc(entryIt->second);
memcpy(oldVals[entryIt->first], entryIt->first, entryIt->second);
}
}
Now i can use it like this:
Foo gBar;
void aFunction()
{
int ar;
char ba[3][3];
// Some code where ar and ba are filled
if(gBar.isChanged(ar))
// Do Something
if(gBar.isChanged(ba))
// Do Something
gBar.endCycle();
}
Is this an efficient way? My goal was a method which is very easy to use inside various cyclically called functions. I cleaned all the init and free logic from the code. Any suggestions? I especially don't like the oldshool malloc, memcpy and memcmp stuff but i don't know any other way how to do it.
Edit: Found a good solution based on Red Alerts suggestions.
I think you can use templates a little more effectively here.
template <typename T>
class Foo
{
public:
static std::map<T*, T> values;
static bool isChanged(T& entry)
{
auto it = values.find(&entry);
if(it == values.end())
{
values[&entry] = entry;
}
else if(entry != it->second)
{
it->second = entry;
return true;
}
return false;
}
};
template <typename T>
std::map<T*, T> Foo<T>::values;
int main() {
int ar = 3;
cout << Foo<int>::isChanged(ar) << endl; // 0
ar = 4;
cout << Foo<int>::isChanged(ar) << endl; // 1
for(auto& value : Foo<int>::values)
cout << value.second << endl; // 4
return 0;
}
This way you get one map per type, and you don't have to worry about inadvertently messing up an alias. You do need to define operator != and have a working copy constructor for your types, but that is much better than blindly using memcmp and memcpy.
You can also make further template specializations for arrays if you need to compare those (will be a bit more code, but nothing very complicated)
Edit: To get you started, this is what your template signature should look like:
template<class T, size_t N> bool isChanged(T(&entry)[N]); //will be called for stack allocated arrays
Or you can use char* to alias all of your values. This will let you use a single map for everything (like you were doing before, but this has no memcpy/memcmp). It will only work for POD. We could manually call the destructor when overwriting the buffer, but since there is no good way to do this in the class's destructor, it's probably best to leave out heap allocated data altogether.
class Foo
{
std::map<char**, char*> values;
public:
~Foo()
{
for(auto& value : values)
{
delete[] value.second;
}
}
template<typename T> bool isChanged(T& entry)
{
char** addr = reinterpret_cast<char**>(&entry);
auto it = values.find(addr);
if(it == values.end())
{
alignas(T) char* oldBuf = new char[sizeof(T)];
T* oldEntry = new(oldBuf) T;
*oldEntry = entry;
values[addr] = oldBuf;
}
else if(entry != *(reinterpret_cast<T*>(it->second)))
{
T* oldEntry = new(it->second) T;
*oldEntry = entry;
return true;
}
return false;
}
};
After many hours i think i found a good solution. The call stays easy and there are no casts. It's a lot more complex than the C-Style version with memcopy but I think its nicer and has also the benefit that it works with complex data not just POD.
class Manager
{
public:
~Manager()
{
funcPtrs.clear();
}
void adFnc(void(*function)())
{
funcPtrs.push_back(function);
}
void runAll()
{
for(auto& val : funcPtrs)
val();
}
private:
std::vector<void (*)()> funcPtrs;
};
Manager gAllClearManager;
template<typename T>
class Data
{
public:
Data()
{
gAllClearManager.adFnc(clearValues);
}
static void clearValues()
{
values.clear();
}
static std::map<T*,std::vector<T>>& getValues() { return values; }
private:
static std::map<T*,std::vector<T>> values;
};
template <typename T>
static bool isChanged(T& entry)
{
const static Data<T>* dataP = new Data<T>();
static std::map<T*,std::vector<T>>& values = dataP->getValues();
auto it = values.find(&entry);
if(it == values.end())
{
values[&entry].push_back(entry);
}
else if(entry != it->second[0])
{
it->second[0] = entry;
return true;
}
return false;
}
template<typename T, size_t N>
bool isChanged(T (&entry)[N])
{
const static Data<T>* dataP = new Data<T>();
static std::map<T*,std::vector<T>>& values = dataP->getValues();
auto it = values.find(entry);
if( it == values.end())
{
for(int i = 0; i < N ; ++i )
values[entry].push_back(entry[i]);
return false;
}
else
{
for(int i = 0; i < N ; ++i )
{
if(it->second[i] != entry[i])
{
for(int j = 0; j < N ; ++j )
{
it->second[j] = entry[j];
}
return true;
}
}
}
return false;
}
template<typename T>
std::map<T*, std::vector<T>> Data<T>::values;
Now i can use it like:
int main() {
int ar;
std::string ba[6];
if(isChange(ar))
// Do something
if(isChange(ba))
// Do something
}
My first template is finally working! :) Thanks again Red Alert.
I'm learning C++, and we were given an exercise to make a stack class using a class template and pointers. I'm not yet fully understanding the implementation of a stack or pointers so I gave it a go and made this class:
template <class T>
class Stack_Class {
public:
T* stack;
int item_quantity;
T* First_item;
int Max_quantity;
Stack_Class(int value);
~Stack_Class();
bool Add(T value);
T Pop();
int GetMax_Quantity();
bool Full();
bool Empty();
};
template <class T>
Stack_Class<T>::Stack_Class(int value) {
if (value > 0) {
stack = new T[value];
First_item = stack;
item_quantity = 0;
Max_quantity = value;
}
}
template <class T>
Stack_Class<T>::~Stack_Class() {
if (First_item) {
delete First_item;
}
}
template<class T>
bool Stack_Class<T>::Add(T num) {
if (item_quantity <Max_quantity) {
*stack = num;
stack++;
item_quantity++;
return true;
}
else return false;
}
template<class T>
T Stack_Class<T>::Pop() {
if (!Empty()) {
item_quantity--;
return stack[item_quantity];
}
return NULL;
}
template<class T>
bool Stack_Class<T>::Empty() {
return (item_quantity == 0);
}
template <class T>
int Stack_Class<T>::GetMax_Quantity() {
return Max_quantity;
}
And the main class would be:
#include <iostream>
#include "Stack_Class.h"
void main() {
Stack_Class<int> intStack(3);
intStack.Add(1);
intStack.Add(2);
intStack.Add(3);
int count = intStack.GetMax_Quantity();
for (int i = 0; i < count; i++) {
std::cout << "Pop No: " << i << " - Elemento: " << intStack.Pop() << std::endl;
}
}
Though as a result I'm getting all random numbers instead of the ones I gave it in intStack. Add, so my question would be I'm implementing the pointer correctly here?
You need to deincrement the stack pointer before you reference it within Pop():
template<class T>
T Stack_Class<T>::Pop(){
if (!Empty()){
item_quantity--;
stack--;
return *stack;
}
return NULL;
}
Your array access stack[item_quantity] does not work because you increment stack in Add. So after construction, the memory pointed to by stack looks like this
0xff65f96f <-- *(stack + 0)
0x0eec604f <-- *(stack + 1)
0x05be0582 <-- *(stack + 2)
0x29b9186e <-- *(stack + 3)
The hexdecimal values represent random garbage coincidentely located in the memory at the time of allocation. This is because memory allocated by new is not initialized to something nice. After adding three values, it looks like this
1 <-- *(stack - 3)
2 <-- *(stack - 2)
3 <-- *(stack - 1)
0x29b9186e <-- *(stack + 0)
0xf66eff06 <-- *(stack + 1)
0x357eb508 <-- *(stack + 2)
In the first call of Pop, you access stack[2] = *(stack + 2), because item_quantity is 2 after deincrementing it. The two consecutive calls to Pop access stack[1] and stack[0]. As you can see above, you never actually reference the values you’ve put into the stack.
You are mixing up the pointer incrementing semantic in the Add method and the indexing semantic in the Pop method.
Since you need the index for the Empty method and so on, I would fix your Add method instead of the Pop as can be seen below.
Otherwise, you would end up still using the indexing in some method(s), but not in other. It would not look consistent to me.
template<class T>
bool Stack_Class<T>::Add(T num){
if (item_quantity <Max_quantity){
stack[item_quantity++] = num;
return true;
}
else return false;
}
Yet another problem in your code is this:
stack = new T[value];
but you seem to only delete the first element in the pointer. That is a guaranteed (and potentially not negligible) memory leak.
Even if you fix all that, your code would not still compile since you are trying to return void, whereas a C++ program should return int, so change this:
void main(){
...
}
to:
int main(){
...
}
... and return an integer like 0 correspondingly.
You would also need to fix this warning:
Stack_Class.h:56:13: warning: converting to non-pointer type ‘int’ from NULL [-Wconversion-null]
return NULL;
^
By for instance change NULL to 0.
Having fixed all that, the output is like this:
Pop No: 0 - Elemento: 3
Pop No: 1 - Elemento: 2
Pop No: 2 - Elemento: 1
You can also see the code running on ideone.
For your convenience, this is the whole working code after those fixes:
template <class T>
class Stack_Class{
public:
T* stack;
int item_quantity;
T* First_item;
int Max_quantity;
Stack_Class(int value);
~Stack_Class();
bool Add(T value);
T Pop();
int GetMax_Quantity();
bool Full();
bool Empty();
};
template <class T>
Stack_Class<T>::Stack_Class(int value){
if (value > 0){
stack = new T[value];
First_item = stack;
item_quantity = 0;
Max_quantity = value;
}
}
template <class T>
Stack_Class<T>::~Stack_Class(){
if (First_item){
delete First_item;
}
}
template<class T>
bool Stack_Class<T>::Add(T num){
if (item_quantity <Max_quantity){
*stack = num;
stack++;
item_quantity++;
return true;
}
else return false;
}
template<class T>
T Stack_Class<T>::Pop(){
if (!Empty()){
item_quantity--;
return stack[item_quantity];
}
return NULL;
}
template<class T>
bool Stack_Class<T>::Empty(){
return (item_quantity == 0);
}
template <class T>
int Stack_Class<T>::GetMax_Quantity(){
return Max_quantity;
}