http://qs321.pair.com?node_id=696736


in reply to Re^5: Runtime introspection: What good is it?
in thread Runtime introspection: What good is it?

Certainly you can use virtual methods/late binding when you only care about the type of one object, but when you care about more than one, it's not so easy. Here's a better example:

Okay. It took a while to drag the steps back from my memories of a former life, and I have a feeling that a few of these steps could be eliminated, but try this:

#include <iostream.h> class Circle; class Polygon; class Shape { public: virtual ~Shape(){}; virtual void ShowType() { cout << "Shape" << endl; } virtual void intersect( Shape *that ) { cout << "Shape:intersect" << endl; } virtual void intersect_( Circle * ); virtual void intersect_( Polygon * ); }; class Polygon : public Shape { public: virtual void ShowType() { cout << "Polygon" << endl; } virtual void intersect_( Polygon *that ) { that->intersect( this ) +; } virtual void intersect( Polygon *that ) { cout << "Intersect Polygon with Polygon" << endl; } void Polygon::intersect_( Circle *that ); virtual void intersect( Shape *that ) { that->intersect_( this ); +} virtual void intersect( Circle *that ) { cout << "Intersect Polygon with Circle" << endl; } }; void Shape::intersect_( Polygon * ) { } class Circle : public Shape { public: virtual void ShowType() { cout << "Circle" << endl; } virtual void intersect_( Circle *that ) { that->intersect( this ); + } virtual void intersect( Circle *that ) { cout << "Intersect Circle with Circle" << endl; } virtual void intersect_( Polygon *that ) { that->intersect( this ) +; } virtual void intersect( Polygon *that ) { cout << "Intersect Circle with Polygon" << endl; } virtual void intersect( Shape *that ) { that->intersect_( this ); +} }; void Shape::intersect_( Circle * ) { } void Polygon::intersect_( Circle *that ) { that->intersect( this ); } int main() { Shape *circle = new Circle; circle->ShowType(); Shape *polygon = new Polygon; polygon->ShowType(); circle->intersect( polygon ); circle->intersect( circle ); polygon->intersect( circle ); polygon->intersect( polygon ); return 1; }

Outputs:

c:\test>696596 Circle Polygon Intersect Circle with Polygon Intersect Circle with Circle Intersect Polygon with Circle Intersect Polygon with Polygon

This evolved in the days before RTTI. Whether I'd use it now in preference to RTTI is debateable. I guess it would depend upon the scale of the project and the affects of enabling RTTI. If it could be localised to some small part of a large project, it might be worth the costs.


Examine what is said, not who speaks -- Silence betokens consent -- Love the truth but pardon error.
"Science is about questioning the status quo. Questioning authority".
In the absence of evidence, opinion is indistinguishable from prejudice.