MapLibre Native Core
All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Friends Macros Pages
actor_ref.hpp
Go to the documentation of this file.
1 #pragma once
2 
3 #include <mbgl/actor/mailbox.hpp>
4 #include <mbgl/actor/message.hpp>
5 
6 #include <memory>
7 
8 namespace mbgl {
9 
22 template <class Object>
23 class ActorRef {
24 public:
25  ActorRef(Object& object_, std::weak_ptr<Mailbox> weakMailbox_)
26  : object(&object_),
27  weakMailbox(std::move(weakMailbox_)) {
28  }
29 
30  template <typename Fn, class... Args>
31  void invoke(Fn fn, Args&&... args) const {
32  if (auto mailbox = weakMailbox.lock()) {
33  mailbox->push(actor::makeMessage(*object, fn, std::forward<Args>(args)...));
34  }
35  }
36 
37  template <typename Fn, class... Args>
38  auto ask(Fn fn, Args&&... args) const {
39  // Result type is deduced from the function's return type
40  using ResultType = std::invoke_result_t<decltype(fn), Object, Args...>;
41 
42  std::promise<ResultType> promise;
43  auto future = promise.get_future();
44 
45  if (auto mailbox = weakMailbox.lock()) {
46  mailbox->push(
48  std::move(promise), *object, fn, std::forward<Args>(args)...
49  )
50  );
51  } else {
52  promise.set_exception(std::make_exception_ptr(std::runtime_error("Actor has gone away")));
53  }
54 
55  return future;
56  }
57 
58 private:
59  Object* object;
60  std::weak_ptr<Mailbox> weakMailbox;
61 };
62 
63 } // namespace mbgl
void invoke(Fn fn, Args &&... args) const
Definition: actor_ref.hpp:31
ActorRef(Object &object_, std::weak_ptr< Mailbox > weakMailbox_)
Definition: actor_ref.hpp:25
auto ask(Fn fn, Args &&... args) const
Definition: actor_ref.hpp:38
std::unique_ptr< Message > makeMessage(Object &object, MemberFn memberFn, Args &&... args)
Definition: message.hpp:94
constexpr ObjectType Object
Definition: type.hpp:89
Definition: actor.hpp:15
Definition: tile_id.hpp:256