// Example of a polymorphic type using a distinct Node template #include #include #include void error(char * m){ cout << m; exit(1);} class poly; template struct node; class poly { public: enum Tag { I, P }; private: union { int i; node * p; }; Tag tag; void check(Tag t){ if (tag!=t) error("bad access");} public: Tag get_tag() { return tag; } int & ival() { check(I); return i; } node * & pval() { check(P); return p; } public: // Creating a new poly poly() { i=0; tag=I; } poly(int ii) { i=ii; tag=I; } poly(node * pp) { p=pp; tag=P; } // Changing the value in a poly void set(int ii) { i=ii; tag=I; } void set(node * pp) { p=pp; tag=P; } void print_preorder(void); }; template struct node { t data; node* next; }; void poly::print_preorder (void) { if (get_tag()==I) cout << ival() << " "; else { // must be pointer to a node node * np = pval(); while (np != NULL){ (np->data).print_preorder(); np = np->next; } } } int main(){ poly p1; poly p2; poly p3; p1.set(11); p1.print_preorder(); cout< n2; node n3; n2.data.set(22); n3.data.set(33); n2.next = &n3; n3.next = NULL; p1.set(&n2); p1.print_preorder(); cout<