-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathsafecallback.hpp
45 lines (39 loc) · 1.28 KB
/
safecallback.hpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
#pragma once
#include <functional>
#include <iostream>
#include <memory>
#include <utility>
template<typename CLASS, typename... ARGS>
class SafeCallback
{
public:
SafeCallback(const std::weak_ptr<CLASS> &object,
const std::function<void(CLASS *, ARGS...)> &function)
: m_object(object)
, m_function(function)
{}
template<typename... CallARGS>
void operator()(CallARGS &&...args) const
{
if (auto ptr = m_object.lock()) {
m_function(ptr.get(), std::forward<CallARGS>(args)...);
} else {
std::cout << "Callback object has been destroyed." << std::endl;
}
}
private:
std::weak_ptr<CLASS> m_object;
std::function<void(CLASS *, ARGS...)> m_function;
};
template<typename CLASS, typename... ARGS>
SafeCallback<CLASS, ARGS...> makeSafeCallback(const std::shared_ptr<CLASS> &object,
void (CLASS::*function)(ARGS...))
{
return SafeCallback<CLASS, ARGS...>(object, function);
}
template<typename CLASS, typename... ARGS>
SafeCallback<CLASS, ARGS...> makeSafeCallback(const std::shared_ptr<CLASS> &object,
void (CLASS::*function)(ARGS...) const)
{
return SafeCallback<CLASS, ARGS...>(object, function);
}