#include #include using namespace std; class Element { public: virtual ~Element() { } }; class This : public Element { public: string thiss() { return "This"; } }; class That : public Element { public: string that() { return "That"; } }; class TheOther : public Element { public: string theOther() { return "TheOther"; } }; void main( void ) { Element* list[] = { new This(), new That(), new TheOther() }; That* ptr; for (int i=0; i < 3; i++) if (ptr = dynamic_cast(list[i])) cout << "do something on " + ptr->that() << '\n'; else cout << "not a That object\n"; } // not a That object // do something on That // not a That object #if 0 class Visitor { public: virtual void visit( class This* ) = 0; virtual void visit( class That* ) = 0; virtual void visit( class TheOther* ) = 0; }; class Element { public: virtual ~Element() { } virtual void accept( Visitor& ) = 0; }; class This : public Element { public: string thiss() { return "This"; } /*virtual*/ void accept( Visitor& v ) { v.visit( this ); } }; class That : public Element { public: string that() { return "That"; } /*virtual*/ void accept( Visitor& v ) { v.visit( this ); } }; class TheOther : public Element { public: string theOther() { return "TheOther"; } /*virtual*/ void accept( Visitor& v ) { v.visit( this ); } }; class ThatVisitor : public Visitor { /*virtual*/ void visit( This* ptr ) { cout << "not a That object\n"; } /*virtual*/ void visit( That* ptr ) { cout << "do something on " + ptr->that() << '\n'; } /*virtual*/ void visit( TheOther* ptr ) { cout << "not a That object\n"; } }; class EveryoneVisitor : public Visitor { /*virtual*/ void visit( This* e ) { cout << "do Everyone on " + e->thiss() << '\n'; } /*virtual*/ void visit( That* e ) { cout << "do Everyone on " + e->that() << '\n'; } /*virtual*/ void visit( TheOther* e ) { cout << "do Everyone on " + e->theOther() << '\n'; } }; void main( void ) { Element* list[] = { new This(), new That(), new TheOther() }; ThatVisitor that; for (int i=0; i < 3; i++) list[i]->accept( that ); cout << '\n'; EveryoneVisitor all; for (i=0; i < 3; i++) list[i]->accept( all ); } // not a That object // do something on That // not a That object // // do Everyone on This // do Everyone on That // do Everyone on TheOther #endif