crl_winapi_async.h 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  1. // This file is part of Desktop App Toolkit,
  2. // a set of libraries for developing nice desktop applications.
  3. //
  4. // For license and copyright information please follow this link:
  5. // https://github.com/desktop-app/legal/blob/master/LEGAL
  6. //
  7. #pragma once
  8. #include <crl/common/crl_common_config.h>
  9. #ifdef CRL_USE_WINAPI
  10. #include <crl/common/crl_common_utils.h>
  11. #include <crl/common/crl_common_sync.h>
  12. #include <type_traits>
  13. namespace crl::details {
  14. void async_plain(void (*callable)(void*), void *argument);
  15. } // namespace crl::details
  16. namespace crl {
  17. template <
  18. typename Callable,
  19. typename Return = decltype(std::declval<Callable>()())>
  20. inline void async(Callable &&callable) {
  21. using Function = std::decay_t<Callable>;
  22. if constexpr (details::is_plain_function_v<Function, Return>) {
  23. using Plain = Return(*)();
  24. const auto copy = static_cast<Plain>(callable);
  25. details::async_plain([](void *passed) {
  26. const auto callable = reinterpret_cast<Plain>(passed);
  27. (*callable)();
  28. }, reinterpret_cast<void*>(copy));
  29. } else {
  30. const auto copy = new Function(std::forward<Callable>(callable));
  31. details::async_plain([](void *passed) {
  32. const auto callable = static_cast<Function*>(passed);
  33. const auto guard = details::finally([=] { delete callable; });
  34. (*callable)();
  35. }, static_cast<void*>(copy));
  36. }
  37. }
  38. } // namespace crl
  39. #endif // CRL_USE_WINAPI