Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
28 changes: 28 additions & 0 deletions src/callback.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@

#include "aligned_storage.hpp"
#include "macros.hpp"
#include "ref_counted.hpp"

#include <new>
#include <stddef.h>
Expand All @@ -41,6 +42,14 @@ class Callback {
STATIC_ASSERT(ALIGN_OF(Storage) >= ALIGN_OF(MemberInvoker));
}

template <class F, class T>
Callback(F func, SharedRefPtr<T> ptr)
: invoker_(new (&storage_) MemberPtrInvoker<F, T>(func, ptr)) {
typedef MemberInvoker<F, T> MemberPtrInvoker;
STATIC_ASSERT(sizeof(Storage) >= sizeof(MemberPtrInvoker));
STATIC_ASSERT(ALIGN_OF(Storage) >= ALIGN_OF(MemberPtrInvoker));
}

template <class F>
explicit Callback(F func)
: invoker_(new (&storage_) FunctionInvoker<F>(func)) {
Expand Down Expand Up @@ -96,6 +105,20 @@ class Callback {
T* object;
};

template <class F, class T>
struct MemberPtrInvoker : public Invoker {
MemberPtrInvoker(F func, const SharedRefPtr<T>& ptr)
: func(func)
, ptr(ptr) {}

R invoke(const Arg& arg) const { return (ptr.get()->*func)(arg); }

Invoker* copy(Storage* storage) { return new (storage) MemberPtrInvoker<F, T>(func, ptr); }

F func;
SharedRefPtr<T> ptr;
};

template <class F>
struct FunctionInvoker : public Invoker {
FunctionInvoker(F func)
Expand Down Expand Up @@ -134,6 +157,11 @@ Callback<R, Arg> bind_callback(R (T::*func)(Arg), T* object) {
return Callback<R, Arg>(func, object);
}

template <class R, class Arg, class T>
Callback<R, Arg> bind_callback(R (T::*func)(Arg), const SharedRefPtr<T>& ptr) {
return Callback<R, Arg>(func, ptr);
}

template <class R, class Arg>
Callback<R, Arg> bind_callback(R (*func)(Arg)) {
return Callback<R, Arg>(func);
Expand Down
4 changes: 2 additions & 2 deletions src/cluster.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -504,7 +504,7 @@ void Cluster::internal_notify_host_up(const Address& address) {
return; // Ignore host
}

if (!prepare_host(host, bind_callback(&Cluster::on_prepare_host_up, this))) {
if (!prepare_host(host, bind_callback(&Cluster::on_prepare_host_up, Cluster::Ptr(this)))) {
notify_host_up_after_prepare(host);
}
}
Expand Down Expand Up @@ -597,7 +597,7 @@ void Cluster::notify_host_add(const Host::Ptr& host) {
return; // Ignore host
}

if (!prepare_host(host, bind_callback(&Cluster::on_prepare_host_add, this))) {
if (!prepare_host(host, bind_callback(&Cluster::on_prepare_host_add, Cluster::Ptr(this)))) {
notify_host_add_after_prepare(host);
}
}
Expand Down