Re: How can I remove dynamic_cast and if statements from this code
snippet?
On 16/11/2011 19:14, Chris Stankevitz wrote:
On Nov 16, 10:52 am, Ian Collins<ian-n...@hotmail.com> wrote:
Something like:
struct Shape {
virtual void write() = 0;};
Ian,
I prefer/require a solution in which the shapes themselves are not
writing out XML -- I want the XML related code restricted to the
"XmlWriter" class in "Library B". This appears to be an overly
draconian requirement in this simple example, but should make more
sense if you consider adding something like a "drawing" or "network"
class that would introduce dependencies on drawing or socket code.
I want drawing/xml/socket code relegated to "Library B" without
compile or link dependencies in "Library A".
Something like the following perhaps?
#include <iostream>
#include <string>
#include <vector>
#include <memory>
struct serializer
{
virtual void write(const std::string& shapeName, const std::string&
dimensionName, float dimensionValue) const = 0;
};
struct shape
{
virtual void write(const serializer& writer) const = 0;
};
struct circle : shape
{
circle(float radius) : radius(radius) {}
virtual void write(const serializer& writer) const
{
writer.write("Circle", "Radius", radius);
}
float radius;
};
struct square : shape
{
square(float edge) : edge(edge) {}
virtual void write(const serializer& writer) const
{
writer.write("Square", "Edge", edge);
}
float edge;
};
struct xml_writer : serializer
{
virtual void write(const std::string& shapeName, const std::string&
dimensionName, float dimensionValue) const
{
std::cout << "<" << shapeName << " " << dimensionName << "=\"" <<
dimensionValue << "\" />\n";
}
};
int main()
{
typedef std::tr1::shared_ptr<shape> shape_ptr;
typedef std::vector<shape_ptr> shapes_t;
shapes_t shapes;
shapes.push_back(shape_ptr(new circle(7.0f)));
shapes.push_back(shape_ptr(new square(42.0f)));
xml_writer w;
for (shapes_t::const_iterator i = shapes.begin(); i != shapes.end(); ++i)
(**i).write(w);
}