Class Templates - Example 10-11 - Class templates with container & iterator classes

// File: ex10-11.cpp

#include <iostream>
using namespace std;

template <typename T, int size = 10> class Iterator;
template <typename T, int size = 10>
class container {
	T array[size];
public:
	friend class Iterator<T, size>;
};

template <typename T, int size>
class Iterator {
	container<T,size>& CR;
	int index;
public:
	Iterator(container<T,size>& cr)
		: CR(cr), index(0) {}
	void reset() { index = 0; }
	int operator++() {
		if(index < size - 1) {
			index++;
			return 1;
		} else return 0; // indicates end of list
	}

	T& current() { return CR.array[index]; }
};

class X {
	int i;
public:
	X(int I = 0) : i(I) {}
	X& operator=(int I) {
		i = I;
		return *this;
	}
	void print() {
		cout << i << endl;
	}
};
class fraction {
	int numer,denom;
public:
	fraction() {}
	fraction(int n, int d) : numer(n),denom(d) {}
	fraction& operator=(const fraction& f)
	{
		numer = f.numer;
		denom = f.denom;
		return *this;
	}
	void print() {
		cout << numer << '/' << denom << endl;
	}
};
const char* suit_name[4] = {"clubs","diamonds","hearts","spades"};
const char* pips_name[13] = {"two","three","four","five","six","seven",
"eight","nine","ten","jack","queen","king","ace"};

class card
{
private:
	int pips, suit;
public:
	card() {}
	card(int n) : pips(n%13), suit(n/13) {}
	card& operator=(const card& c)
	{
		pips = c.pips;
		suit = c.suit;
		return *this;
	}
	void print()
	{
		cout << pips_name[pips] << " of " << suit_name[suit] << endl;
	}
};
int main() {
	int i;
	container<X> XC;
	Iterator<X> it_X(XC);
	for(i = 0; i < 10; i++) {
		it_X.current() = i;
		++it_X;
	}
	it_X.reset();
	do it_X.current().print(); while(++it_X);

	container<fraction,3> fractionC;
	Iterator<fraction,3> it_fraction(fractionC);
	for(i = 0; i < 3; i++) {
		it_fraction.current() = fraction(i+1,i+2);
		++it_fraction;
	}
	it_fraction.reset();
	do it_fraction.current().print(); while(++it_fraction);

	container<card,5> cardC;
	Iterator<card,5> it_card(cardC);
	for(i = 0; i < 5; i++) {
		it_card.current() = card(3*i+5);
		++it_card;
	}
	it_card.reset();
	do it_card.current().print(); while(++it_card);
	return 0;
}

/***** Output *****
0
1
2
3
4
5
6
7
8
9
1/2
2/3
3/4
seven of clubs
ten of clubs
king of clubs
three of diamonds
six of diamonds
*********************/