mirror of
https://github.com/Naios/continuable.git
synced 2025-12-07 17:26:47 +08:00
add make_weak_wrapped_callback
This commit is contained in:
parent
aa03a00f92
commit
d9307fa8b6
@ -51,6 +51,19 @@ namespace detail
|
||||
template<typename _CTy>
|
||||
using unwrap_callback = do_unwrap_callback<::fu::argument_type_of_t<_CTy>>;
|
||||
|
||||
template<typename... Args>
|
||||
struct WeakProxyFactory
|
||||
{
|
||||
static Callback<Args...> CreateProxy(WeakCallback<Args...> const& weak_callback)
|
||||
{
|
||||
return [=](Args&&... args)
|
||||
{
|
||||
if (auto const callback = weak_callback.lock())
|
||||
(*callback)(args...);
|
||||
};
|
||||
}
|
||||
};
|
||||
|
||||
} // detail
|
||||
|
||||
template<typename _CTy>
|
||||
@ -70,4 +83,18 @@ inline shared_callback_of_t<_CTy>
|
||||
(std::forward<callback_of_t<_CTy>>(callback));
|
||||
}
|
||||
|
||||
template<typename... Args>
|
||||
inline auto make_weak_wrapped_callback(WeakCallback<Args...> const& wrapped_callback)
|
||||
-> Callback<Args...>
|
||||
{
|
||||
return detail::WeakProxyFactory<Args...>::CreateProxy(wrapped_callback);
|
||||
}
|
||||
|
||||
template<typename... Args>
|
||||
inline auto make_weak_wrapped_callback(SharedCallback<Args...> const& wrapped_callback)
|
||||
-> Callback<Args...>
|
||||
{
|
||||
return make_weak_wrapped_callback<Args...>(WeakCallback<Args...>(wrapped_callback));
|
||||
}
|
||||
|
||||
#endif /// _CALLBACK_H_
|
||||
|
||||
@ -42,6 +42,7 @@ class WeakCallbackContainer
|
||||
struct ProxyFactory<_CTy, std::tuple<Args...>>
|
||||
{
|
||||
// Creates a weak proxy callback which prevents invoking to an invalid context.
|
||||
// Removes itself from the owner with the given handler.
|
||||
static callback_of_t<_CTy> CreateProxy(std::weak_ptr<WeakCallbackContainer> const& weak_owner,
|
||||
size_t const handle, weak_callback_of_t<_CTy> const& weak_callback)
|
||||
{
|
||||
@ -82,7 +83,7 @@ public:
|
||||
}
|
||||
|
||||
template<typename _CTy>
|
||||
auto operator()(_CTy&& callback)
|
||||
auto Wrap(_CTy&& callback)
|
||||
-> callback_of_t<_CTy>
|
||||
{
|
||||
// Create the shared callback
|
||||
@ -98,6 +99,13 @@ public:
|
||||
return std::move(proxy);
|
||||
}
|
||||
|
||||
template<typename _CTy>
|
||||
inline auto operator()(_CTy&& callback)
|
||||
-> decltype(Wrap(std::declval<_CTy>()))
|
||||
{
|
||||
return Wrap(std::forward<_CTy>(callback));
|
||||
}
|
||||
|
||||
boost::optional<handle_t> GetLastCallbackHandle() const
|
||||
{
|
||||
if (handle == 0L)
|
||||
|
||||
7
test.cpp
7
test.cpp
@ -92,5 +92,12 @@ int main(int argc, char** argv)
|
||||
// This will never be executed because the CallbackContainer was deallocated and its weak callback proxies are crash safe.
|
||||
weak_cb_test();
|
||||
|
||||
SharedCallback<> weak_2 = make_shared_callback([]
|
||||
{
|
||||
|
||||
});
|
||||
|
||||
auto wrapped = make_weak_wrapped_callback(weak_2);
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
||||
Loading…
x
Reference in New Issue
Block a user