Re: Cast best practice question

Tech-Archive recommends: Repair Windows Errors & Optimize Windows Performance



Thanks, Yes the visitor pattern part doesn't involve any cast. I mentioned
Visitor pattern just for expaining why I didn't create a struct but a vector.


"Igor Tandetnik" wrote:

nick <nick@xxxxxxxxxxxxxxxxxxxxxxxxx> wrote:
There are 100 to 200 Derived. And I used visitor pattern, so I can do
for (vector<base*>::size_type i; i<v.size(); i++)
v.visitor(some_visitor);
But I had to defined a big enum to get particular element of v.

A canonical implementation of Visitor pattern goes something like this:

class Visitor;

class Visitable {
public:
virtual void accept(Visitor*) = 0;
};

template <typename T>
class Element<T> : public Visitable {
public:
T getVal() {return val;}
void accept(Visitor* v) {
v->visit(this);
}
private:
T val;
};

class Collection : public Visitable {
void accept(Visitor* v) {
for (vector<Visitable*>::iterator it = coll.begin();
it != coll.end(); ++it) {
(*it)->accept(v);
}
}
private:
vector<Visitable*> coll;
};

class Visitor {
public:
virtual void visit(Element<int>*) = 0;
virtual void visit(Element<string>*) = 0;
// and so on for each type you want to recognize
};

As you see, this implementation does not involve any casts anywhere,
thanks to the magical wonders of virtual dispatch.
--
With best wishes,
Igor Tandetnik

With sufficient thrust, pigs fly just fine. However, this is not
necessarily a good idea. It is hard to be sure where they are going to
land, and it could be dangerous sitting under them as they fly
overhead. -- RFC 1925



.



Relevant Pages

  • Re: Cast best practice question
    ... A canonical implementation of Visitor pattern goes something like this: ... void accept{ ...
    (microsoft.public.vc.language)
  • Re: When and where to use Visitor Pattern?
    ... Visitor pattern allows exactly that. ... > abstract void visitIntExp; ... >class IntExp extends Expression ...
    (comp.object)
  • Re: Static vs Dynamic
    ... >> Do you have an example of a good OO design that Java forces you to ... > static void m{ ... that's not an implementation of the Visitor Pattern. ... implement the visitor pattern in Lisp because of run-time dispatching, ...
    (comp.lang.lisp)
  • Re: Double Dispatch Problem: Mobile Creatures and Projectiles in a Game World
    ... without downcasting, double dispatch, or the Visitor pattern? ... Liquid and Solid were subclasses of Thing; Take was a subclass of Verb. ... void accept{ ... www.EdmundKirwan.com - Home of The Fractal Class Composition. ...
    (comp.object)
  • Re: "virtual pair"
    ... Valery wrote: ... > struct S; ... The Visitor Pattern would be my first choice to consider to implement ... void go1{ ...
    (comp.lang.cpp)