c++ - Returning a value from Visitor pattern -


i have hierarchy follows:

         class element{ public : virtual void accept(visitor&) = 0                  protected : element();   int num;           };           class elementa : public element{                  public : elementa();                   void accept(visitor& v) {v.visit(this};}          };           class elementb : public element{                  public : elementb();                   void accept(visitor& v) {v.visit(this};}            class visitor{                  public: void visit(elementa*);                  void visit(elementb*);          }; 

edit: required add method int getnum() hierarchy provide value of num. however, need entire hierarchy compiled again , not allowed that. have change design of hierarchy in way recompilation of hierarchy not needed.

what want not possible in cleanly designed way. have no idea, why complete recompile of hierarchy such problem, there solution technically possible without employing ub hacks reinterpret_casting access protection away , other hacks.

int visitor::getnum(element* pe) {    //define pick-pocket... ;)   struct elementnumaccessor : private element   {     elementnumaccessor(element const& e) : element(e) {}        int getnum() { return num; }      void accept(visitor&); //has declared, needs not defined   };    //...and let him work:   elementnumaccessor ea(*pe);   return ea.getnum(); } 

this soultion in action: http://ideone.com/e1chsx
exploits fact protected access transitive, comes @ expense of copy of each element want num from. made struct function local class, nobody gets idea use other purpose.

but bear in mind technique hack, exploit of language feature not meant used way.

my advice be: if hierarchy entangled in program changing leaves recompilation horror, it's time refactor program reduce compiletime dependencies , changes have do.


Comments

Popular posts from this blog

monitor web browser programmatically in Android? -

Shrink a YouTube video to responsive width -

wpf - PdfWriter.GetInstance throws System.NullReferenceException -