From b36d072ad7a7b9c6e30fcb25d6bbb001a8393468 Mon Sep 17 00:00:00 2001 From: HampusM Date: Sun, 10 Apr 2022 17:20:49 +0200 Subject: refactor: add factory class & make DI container return unique ptrs --- src/DI/container.tpp | 26 ++++++++++++++------------ 1 file changed, 14 insertions(+), 12 deletions(-) (limited to 'src/DI/container.tpp') diff --git a/src/DI/container.tpp b/src/DI/container.tpp index 54b09c6..13397bc 100644 --- a/src/DI/container.tpp +++ b/src/DI/container.tpp @@ -15,23 +15,25 @@ BindingBuilder::BindingBuilder(Container *container) noexcept template template -requires std::derived_from +requires Abstract && std::derived_from void BindingBuilder::to() noexcept { using Wrapper = ObjectWrapper; - auto wrapper = Container::Ptr(new Wrapper(*_container)); + auto wrapper = Container::WrapperPtr(new Wrapper(*_container)); _container->add(ObjectType(), std::dynamic_pointer_cast(wrapper)); } template -void BindingBuilder::to_factory(Interface func) noexcept +template +requires IsFactory && std::constructible_from +void BindingBuilder::to_factory(FactoryFunc factory) noexcept { using Wrapper = FunctionWrapper; - auto wrapper = Container::Ptr(new Wrapper(func)); + auto wrapper = Container::WrapperPtr(new Wrapper(factory)); _container->add(ObjectType(), std::dynamic_pointer_cast(wrapper)); @@ -45,7 +47,7 @@ auto Container::bind() noexcept -> BindingBuilder template requires Abstract -auto Container::get() const noexcept -> Ptr +auto Container::get() const noexcept -> std::unique_ptr { ObjectType interface_type; @@ -57,18 +59,18 @@ auto Container::get() const noexcept -> Ptr exit(EXIT_FAILURE); } - auto wrapper = - std::dynamic_pointer_cast>>(_bindings.at(interface_type)); + auto wrapper = std::dynamic_pointer_cast>>( + _bindings.at(interface_type)); return wrapper->get(); } -template -requires Function -auto Container::get() const noexcept -> Interface +template +requires IsFactory +auto Container::get() const noexcept -> AFactory { - auto wrapper = std::dynamic_pointer_cast>( - _bindings.at(ObjectType())); + auto wrapper = std::dynamic_pointer_cast>( + _bindings.at(ObjectType())); return wrapper->get(); } -- cgit v1.2.3-18-g5258