1// excerpts from http://code.google.com/p/muduo/
2//
3// Use of this source code is governed by a BSD-style license
4// that can be found in the License file.
5//
6// Author: Shuo Chen (giantchen at gmail dot com)
7
8#ifndef MUDUO_BASE_WEAKCALLBACK_H
9#define MUDUO_BASE_WEAKCALLBACK_H
10
11#include <functional>
12#include <memory>
13
14namespace muduo
15{
16
17// A barely usable WeakCallback
18
19template<typename CLASS, typename... ARGS>
20class WeakCallback
21{
22 public:
23
24  WeakCallback(const std::weak_ptr<CLASS>& object,
25               const std::function<void (CLASS*, ARGS...)>& function)
26    : object_(object), function_(function)
27  {
28  }
29
30  // Default dtor, copy ctor and assignment are okay
31
32  void operator()(ARGS&&... args) const
33  {
34    std::shared_ptr<CLASS> ptr(object_.lock());
35    if (ptr)
36    {
37      function_(ptr.get(), std::forward<ARGS>(args)...);
38    }
39  }
40
41 private:
42
43  std::weak_ptr<CLASS> object_;
44  std::function<void (CLASS*, ARGS...)> function_;
45};
46
47template<typename CLASS, typename... ARGS>
48WeakCallback<CLASS, ARGS...> makeWeakCallback(const std::shared_ptr<CLASS>& object,
49                                              void (CLASS::*function)(ARGS...))
50{
51  return WeakCallback<CLASS, ARGS...>(object, function);
52}
53
54template<typename CLASS, typename... ARGS>
55WeakCallback<CLASS, ARGS...> makeWeakCallback(const std::shared_ptr<CLASS>& object,
56                                              void (CLASS::*function)(ARGS...) const)
57{
58  return WeakCallback<CLASS, ARGS...>(object, function);
59}
60
61}
62
63#endif
64