1. stackT.h
#ifndef STACKT_H_
#define STACKT_H_
template<class T> class stackIter;
template<class T>
class stackt
{
enum{ssize = 100};
T stack[ssize];
int top;
public:
stackt() : top(0)
{
stack[top] = 0;
}
void push(const T& i)
{
if(top < ssize)
{
stack[top++] = i;
}
}
T pop()
{
return stack[top > 0 ? --top : top];
}
friend class stackIter<T>;
};
template<class T>
class stackIter
{
stackt<T>& S;
int index;
public:
stackIter(stackt<T>& is) : S(is), index(0){}
T& operator++()
{
if (index < S.top - 1)
{
index++;
}
return S.stack[index];
}
T& operator++(int)
{
int returnIndex = index;
if (index < S.top - 1)
{
index++;
}
return S.stack[returnIndex];
}
};
#endif
2. main.cpp
#include "stackT.h"
#include <iostream>
using namespace std;
template<class T, class R>
void applist(stackt<T>& t1, R (T::*f)(), int size)
{
stackIter<T> it(t1);
for (int i = 0; i < size; i++)
{
T& t = it++;
(t.*f)();
}
}
template<class T, class R, class A1, class A2>
void applist(stackt<T>& t1, R (T::*f)(A1, A2), A1 a1, A2 a2, int sz)
{
stackIter<T> it(t1);
for (int i = 0; i < sz; i++)
{
T& t = it++;
(t.*f)(a1, a2);
}
}
class gromit
{
int arf;
public:
gromit(int Arf = 1) : arf(Arf + 1){}
void speek()
{
cout << "speek() : " << arf << endl;
}
int sleep(char, double)
{
cout << "zzz..." << endl;
return 0;
}
};
int main()
{
stackt<gromit> dogs;
const int sz = 5;
for (int i = 0; i < sz; i++)
{
dogs.push(*new gromit(i));
}
applist(dogs, &gromit::speek, sz);
applist(dogs, &gromit::sleep, 'z', 3.0, sz);
system("pause");
return 1;
}