From 6bea1363c9b3f01fec5b54fd0f3a3ee91fa16672 Mon Sep 17 00:00:00 2001 From: HampusM Date: Tue, 29 Mar 2022 17:14:47 +0200 Subject: refactor: replace repeated code in factories --- src/bootstrap.cpp | 51 ++++++++++++++++++++++++++++++++------------------- 1 file changed, 32 insertions(+), 19 deletions(-) (limited to 'src') diff --git a/src/bootstrap.cpp b/src/bootstrap.cpp index e8315bd..49808d6 100644 --- a/src/bootstrap.cpp +++ b/src/bootstrap.cpp @@ -33,10 +33,22 @@ #include "util/function.hpp" +#include #include #include #include +template +concept abstract = std::is_abstract_v; + +template +requires abstract && std::derived_from && + std::constructible_from +auto construct_as_interface(Params &&...parameters) -> std::shared_ptr +{ + return std::dynamic_pointer_cast(std::make_shared(parameters...)); +} + Container bootstrap() noexcept { auto container = Container(); @@ -60,62 +72,63 @@ Container bootstrap() noexcept auto status_updater = container.get()(statusline, generation_tracker); - return std::dynamic_pointer_cast( - std::make_shared(window, scene, cursor_controller, statusline, - generation_tracker, status_updater)); + return construct_as_interface(window, scene, cursor_controller, + statusline, generation_tracker, + status_updater); })); container.bind().to_factory( [](const uint32_t &seed) { - return std::dynamic_pointer_cast( - std::make_shared(seed)); + return construct_as_interface( + seed); }); container.bind().to_factory( []() { - return std::dynamic_pointer_cast( - std::make_shared(std::make_unique())); + return construct_as_interface( + std::make_shared()); }); container.bind>().to_factory( [](const Bounds &bounds) { - return std::dynamic_pointer_cast>( - std::make_shared>(bounds)); + return construct_as_interface, + Matrix>(bounds); }); container.bind().to_factory(normalize_lambda( [&container](const std::shared_ptr &cursor_controller, const std::shared_ptr &window) { - return std::dynamic_pointer_cast( - std::make_shared(container.get>(), - cursor_controller, window)); + auto matrix_factory = container.get>(); + + return construct_as_interface(matrix_factory, + cursor_controller, window); })); container.bind().to_factory( [](const std::shared_ptr &cursor_controller, const std::shared_ptr &window) { - return std::dynamic_pointer_cast( - std::make_shared(cursor_controller, window)); + return construct_as_interface(cursor_controller, + window); }); container.bind().to_factory( - [](const std::shared_ptr &status_line, + [](const std::shared_ptr &statusline, const std::shared_ptr &generation_tracker) { - return std::dynamic_pointer_cast( - std::make_shared(status_line, generation_tracker)); + return construct_as_interface( + statusline, generation_tracker); }); container.bind().to_factory( [](bool is_paused) { - return std::dynamic_pointer_cast( - std::make_shared(is_paused)); + return construct_as_interface( + is_paused); }); return container; -- cgit v1.2.3-18-g5258