You can use the template. In your example, this would be:
class DerivedA; class DerivedB; class Visitor { public: virtual void visitA( DerivedA& a ) = 0; virtual void visitB( DerivedB& b ) = 0; }; class Base { public: virtual void Accept( Visitor& visitor ) = 0; }; class DerivedA : public Base { public: virtual void Accept( Visitor& visitor ) { visitor.visitA( *this ); } }; class DerivedB : public Base { public: virtual void Accept( Visitor& visitor ) { visitor.visitB( *this ); } };
Then from AManager or BManager:
void Handle(Base* pFoo) { class MyVisitor : public Visitor { public: virtual void visitA( DerivedA& a ) {
The drawback of the visitor template is that you will need to define a new class of visitors each time you want to do something specific.
You can also think about this (but I definitely recommend to visitors, really welcome if you add DerivedC later or want to share some specific operation through the common classes of visitors).
class Base { public: virtual DerivedA* GetAsA() = 0; virtual DerivedB* GetAsB() = 0; }; class DerivedA : public Base { public: virtual DerivedA* GetAsA() { return this; } virtual DerivedB* GetAsB() { return NULL; } }; class DerivedB : public Base { public: virtual DerivedA* GetAsA() { return NULL; } virtual DerivedB* GetAsB() { return this; } };
Then from AManager or BManager:
void Handle(Base* pFoo) { if ( pFoo->GetAsA() ) {
jpo38
source share