Skip to content

Instantly share code, notes, and snippets.

@deanberris
Created November 9, 2012 13:49
Show Gist options
  • Save deanberris/4045739 to your computer and use it in GitHub Desktop.
Save deanberris/4045739 to your computer and use it in GitHub Desktop.
polymorphism-2
#include <iostream>
#include <memory>
#include <vector>
#include <utility>
/* Same definition of Object, Book, and Door as before */
class object_concept_t {
public:
virtual ~object_concept_t() = default;
virtual void print() = 0;
virtual object_concept_t* copy() const = 0;
};
template <class T>
class model_t : public object_concept_t {
T t;
public:
model_t(T const &t) : t{t} {}
model_t(T &&t) : t{std::move(t)} {}
virtual void print() { t.print(); }
virtual model_t* copy() const { return new model_t{*this}; }
};
class object_t {
std::unique_ptr<object_concept_t> object;
friend void print(object_t const& o) { o.object->print(); }
public:
object_t() = default;
object_t(object_t const &other) : object{other.object->copy()} {}
object_t(object_t &&other) : object{std::move(other.object)} {}
template <class O>
object_t(O &&o) : object{new model_t<O>{o}} {}
object_t& operator= (object_t const &other) { object_t copy{other}; copy.swap(*this); return *this; }
object_t& operator= (object_t &&other) { other.swap(*this); return *this; }
void swap(object_t &other) noexcept {
using std::swap;
swap(other.object, this->object);
}
};
int main(int argc, const char * argv[])
{
std::vector<object_t> objects{
Object{},
Door{"simple"},
Book{"Dean Michael Berris", "C++ Soup"}
};
for (const auto &object : objects) {
print(object);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment