Update example to use type erased polymorphism technique

This commit is contained in:
McMassiveNZ
2023-06-29 22:50:21 +02:00
parent 9bcbe577a9
commit 4a17314eaa
5 changed files with 83 additions and 77 deletions

View File

@@ -1,6 +1,7 @@
#pragma once
#include <memory>
#include <optional>
namespace starter_window
{
@@ -17,11 +18,41 @@ struct WindowCreateParams
class Window
{
public:
virtual ~Window() = default;
virtual void PumpMessages() = 0;
virtual bool ShouldClose() = 0;
template<typename T>
Window(T t)
: self{std::make_unique<model_t<T>>(std::move(t))}
{
}
~Window() = default;
Window(Window&&) = default;
Window& operator=(Window&&) = default;
Window(const Window&) = delete;
Window operator=(const Window&) = delete;
friend void PumpMessages(Window& window) { window.self->PumpMessages_(); }
friend bool ShouldClose(const Window& window) { return window.self->ShouldClose_(); }
private:
struct concept_t
{
virtual ~concept_t() = default;
virtual void PumpMessages_() = 0;
virtual bool ShouldClose_() const = 0;
};
template<typename T>
struct model_t final : concept_t
{
model_t(T&& data) : m_data(std::move(data)) {}
virtual void PumpMessages_() override{ PumpMessages(m_data); }
virtual bool ShouldClose_() const override { return ShouldClose(m_data); }
T m_data;
};
std::unique_ptr<concept_t> self;
};
}
std::unique_ptr<starter_window::Window> swCreateWindow(starter_window::WindowCreateParams params);
starter_window::Window swCreateWindow(starter_window::WindowCreateParams params);