Re: Cast best practice question
- From: nick <nick@xxxxxxxxxxxxxxxxxxxxxxxxx>
- Date: Mon, 17 Apr 2006 14:18:02 -0700
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
- References:
- Re: Cast best practice question
- From: Igor Tandetnik
- Re: Cast best practice question
- From: Igor Tandetnik
- Re: Cast best practice question
- From: Igor Tandetnik
- Re: Cast best practice question
- Prev by Date: Re: Passing function pointer
- Next by Date: Re: Passing function pointer
- Previous by thread: Re: Cast best practice question
- Next by thread: Passing function pointer
- Index(es):
Relevant Pages
|