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