Skip to content

Instantly share code, notes, and snippets.

@qrealka
Created April 18, 2018 12:50
Show Gist options
  • Save qrealka/88e122a812ca8b8bc0a114481f9dcf8b to your computer and use it in GitHub Desktop.
Save qrealka/88e122a812ca8b8bc0a114481f9dcf8b to your computer and use it in GitHub Desktop.
/*
* from discussion https://twitter.com/krisjusiak/status/981505271796256768
*/
#include <memory>
#include <type_traits>
#include <utility>
volatile int state = 0;
class Drawable {
struct concept {
virtual ~concept() = default;
virtual void draw() const = 0;
};
template <class T>
struct model final : concept {
T _instance;
template <class U>
model(U&& x) : _instance{std::forward<U>(x)} {}
void draw() const override { _instance.draw(); }
};
std::unique_ptr<concept> _self;
public:
template <class T>
Drawable(T&& x) : _self{std::make_unique<model<std::decay_t<T>>>(std::forward<T>(x))} {}
void draw() const { _self->draw(); }
};
struct Square {
void draw() const { state = 1; }
};
struct Circle {
void draw() const { state = 2; }
};
const auto draw = [](auto const& drawable) { drawable.draw(); };
int main() {
Drawable d0{Circle{}};
Drawable d1{Square{}};
d0.draw();
d1.draw();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment