Skip to content

Instantly share code, notes, and snippets.

@kcris
Last active December 31, 2015 17:29
Show Gist options
  • Save kcris/8019978 to your computer and use it in GitHub Desktop.
Save kcris/8019978 to your computer and use it in GitHub Desktop.
Polymorphism involving objects with value semantics (C++)
/*
(c) 2013 +++ Filip Stoklas, aka FipS, http://www.4FipS.com +++
THIS CODE IS FREE - LICENSED UNDER THE MIT LICENSE
ARTICLE URL: http://forums.4fips.com/viewtopic.php?f=3&t=1194
*/
#include <iostream>
#include <vector>
#include <memory>
struct Circle
{
void draw(std::ostream &out) { out << "Circle::draw()\n"; }
};
struct Square
{
void draw(std::ostream &out) { out << "Square::draw()\n"; }
};
struct List
{
template <typename Shape_T>
void push(Shape_T shape)
{
_shapes.emplace_back(new Slot<Shape_T>(std::move(shape)));
}
void draw(std::ostream &out)
{
for(auto &shape : _shapes)
{
shape->draw(out);
}
}
private:
struct If
{
virtual ~If() {}
virtual void draw(std::ostream &out) = 0;
};
template <typename Shape_T>
struct Slot : public If
{
virtual void draw(std::ostream &out) { shape.draw(out); }
Slot(Shape_T shape) : shape(shape) {}
Shape_T shape;
};
typedef std::unique_ptr<If> If_ptr;
std::vector<If_ptr> _shapes;
};
int main()
{
Square s;
Circle c;
List l;
l.push(s);
l.push(c);
l.push(c);
l.push(c);
l.draw(std::cout);
return 0;
}
// Compiled under Visual C++ 2012, output:
// Square::draw()
// Circle::draw()
// Circle::draw()
// Circle::draw()
//
//original found at
//http://code.4fips.com/browse/forums/2013/polymorphism_value_semantics_sample.cpp/
//
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment