Created
April 18, 2018 12:50
-
-
Save qrealka/88e122a812ca8b8bc0a114481f9dcf8b to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
* 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