🛠️🐜 Antkeeper superbuild with dependencies included https://antkeeper.com
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

56 lines
1.7 KiB

  1. # Crash Course: service locator
  2. <!--
  3. @cond TURN_OFF_DOXYGEN
  4. -->
  5. # Table of Contents
  6. * [Introduction](#introduction)
  7. * [Service locator](#service-locator)
  8. <!--
  9. @endcond TURN_OFF_DOXYGEN
  10. -->
  11. # Introduction
  12. Usually service locators are tightly bound to the services they expose and it's
  13. hard to define a general purpose solution.<br/>
  14. This tiny class tries to fill the gap and to get rid of the burden of defining a
  15. different specific locator for each application.
  16. # Service locator
  17. The service locator API tries to mimic that of `std::optional` and adds some
  18. extra functionalities on top of it such as allocator support.<br/>
  19. There are a couple of functions to set up a service, namely `emplace` and
  20. `allocate_emplace`:
  21. ```cpp
  22. entt::locator<interface>::emplace<service>(argument);
  23. entt::locator<interface>::allocate_emplace<service>(allocator, argument);
  24. ```
  25. The difference is that the latter expects an allocator as the first argument and
  26. uses it to allocate the service itself.<br/>
  27. Once a service has been set up, it's retrieved using the value function:
  28. ```cpp
  29. interface &service = entt::locator<interface>::value();
  30. ```
  31. Since the service may not be set (and therefore this function may result in an
  32. undefined behavior), the `has_value` and `value_or` functions are also available
  33. to test a service locator and to get a fallback service in case there is none:
  34. ```cpp
  35. if(entt::locator<interface>::has_value()) {
  36. // ...
  37. }
  38. interface &service = entt::locator<interface>::value_or<fallback_impl>(argument);
  39. ```
  40. All arguments are used only if necessary, that is, if a service doesn't already
  41. exist and therefore the fallback service is constructed and returned. In all
  42. other cases, they are discarded.<br/>
  43. Finally, to reset a service, use the `reset` function.