Re: How can I remove dynamic_cast and if statements from this code snippet?
On Nov 16, 10:37 am, Chris Stankevitz <chrisstankev...@gmail.com>
wrote:
Hello,
I would like to remove the "dynamic_cast" and "if" statements from the
code below. I believe some people would describe this as making the
code "polymorphic". Can you recommend a way to do this without
modifying the original classes in "Library A"?
My intention is to create an "XML Writer" class(es) for shapes without
putting "XML code" in the base classes. I plan to use a similar
pattern for drawing and other tasks my application has to perform on
Shape objects.
The adapted visitor pattern that people have shown here is one good
way to solve this. Another you could consider though is a multi-
dispatch mechanism separate from the two parts. This would retain the
dynamic_cast stuff, but you can use TMP to build that. Review _Modern
C++ Design_ by Alexandrescu.
Basically, something like so:
template < typename Seq, typename Enable = void >
struct dispatcher
{
typedef typename front<Seq>::type my_type;
typedef typename pop_front<Seq>::type next_seq;
static void write(Shape const& sh, Writer & wr)
{
if (my_type const* csh = dynamic_cast<my_type const*>(&sh))
wr.write(*csh);
else
dispatcher<next_seq>::write(sh);
}
}
template < typename Seq >
struct dispatcher<Seq, typename enable_if<empty<Seq> >::type>
{
static void write(Shape const&, Writer &) { throw
std::runtime_error("Unknown shape type."); }
};
void write_shape(Shape const& sh, Writer & w)
{
typedef vector<Square, Circle> shape_seq;
dispatcher<shape_seq>::write(sh,w);
}