Positive polymorphism

I read Concept Based Inheritance in C ++. I have an attached sample code for everyone. I basically ask if this concept is correct? I am new to this, so I just put off what is on my mind. Any comments / criticisms are welcome.

#include "stdafx.h" #include <memory> #include <vector> #include <algorithm> #include <iostream> using namespace std; struct Point{ int x; int y; }; class graphics_surface{ class drawable_concept{ public: virtual void draw(Point const& coordinate) {}; virtual ~drawable_concept() {}; }; template<class T> class drawable_model : public drawable_concept{ public: drawable_model(T& item) : item_(item){} void draw(Point const& coordinate){ item_.draw(coordinate); } ~drawable_model(){} private: T item_; }; public: template<class T> void push_back(T& drawable){ v_.push_back(shared_ptr<drawable_concept>( new drawable_model<T>(drawable))); } void draw(Point const& coordinate) { for_each(v_.begin(), v_.end(), [&](shared_ptr<drawable_concept>& concept){ concept->draw(coordinate); }); } private: vector<shared_ptr<drawable_concept>> v_; }; struct triangle{ void draw(Point const& p){ cout << "Triangle: " << px << "," << py << endl; } }; struct square{ void draw(Point const& p){ cout << "Sqaure: " << px << "," << py << endl; } }; int _tmain(int argc, _TCHAR* argv[]) { Point p; px = 1; py = 2; graphics_surface surface; surface.push_back(triangle()); surface.draw(p); return 0; } 

Thanks in advance.

Blair

+7
c ++ polymorphism duck-typing
source share
3 answers

A few points:

  • I see no good reason to put drawable_concept or drawable_model inside graphics_surface - you simply prohibit reusing something that is potentially useful in other types of containers ...

  • you have problems with const

    • draw should probably be const (and should not follow semicolon definitions ;-)

    • drawable_model(T& item) should take item with const reference

    • push_back(T& drawable) shoudl take drawable using const reference

  • you should use make_shared for exception safety

  • the functionality of "factory" may be better divided into a separate function, rather than enclosed inside push_back

+2
source share

Your approach here is more about erasing styles than about concept-based programming. This is an extension of the idea used by boost :: any. Concepts are a set of constraints on the type required by a class or function template. STL has concepts such as ForwardIterator and InputIterator. These are limitations that are expected to be true for parameters passed, for example, to some std algorithms.

+1
source share

The triangle and square classes must inherit from graphics_surface::drawable_concept . Read about virtual method tables .

See also wikipage in C ++ Concept .

-3
source share

All Articles