/* This file illustrates two ways of achieving polymorphism in C++, neither form is complete satisfactory. The first method uses macros to do advanced copy-and-paste (see the define SWAP lines below). The second methods uses templates to define type variables. But further investigation reveals that this is just a way of automatically telling the compiler to generate several different versions of the same program. C++ can not tell when a function should be compiled as polymorphic. */ #define SWAP(a,b,type,temp) type temp = a; \ a = b; \ b = temp; #include template class cell {public: headType head; cell *tail; cell(headType h, cell *t) { head = h; tail = t; } ~cell() { if (tail != 0) delete(tail); } }; // end polymorphic class cell template int length(cell *L) // length of a polymorphic list { if (L == 0) return 0; // null? else return 1 + length(L->tail); } int main() { cell *intlist; cell *strlist; cell *flist; intlist = new cell(3, new cell(5, new cell(7,0))); strlist = new cell("abc", new cell("def", 0)); flist = new cell(1.1,new cell(2.2,0)); // cout is already polymorphic! cout << length(intlist) << " " << length(strlist) << " " << length(flist) << "\n"; int x = 3; int y = 4; float a = 3.14; float b = 5.6; SWAP(x,y,int,temp1) SWAP(a,b,float,temp2) cout << " x == " << x << " and a == " << a << "\n"; return 0; } // end main // whenever a polymorphic class is refered to in code, it must // be instantiated.