notify.h 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. /*
  2. * notify.h - abstract class for things that notify about their changes
  3. * Copyright (C) 2017 caryoscelus
  4. *
  5. * This program is free software: you can redistribute it and/or modify
  6. * it under the terms of the GNU General Public License as published by
  7. * the Free Software Foundation, either version 3 of the License, or
  8. * (at your option) any later version.
  9. *
  10. * This program is distributed in the hope that it will be useful,
  11. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  13. * GNU General Public License for more details.
  14. *
  15. * You should have received a copy of the GNU General Public License
  16. * along with this program. If not, see <http://www.gnu.org/licenses/>.
  17. */
  18. #ifndef __CORE__NODE__NOTIFY_H__35072B50
  19. #define __CORE__NODE__NOTIFY_H__35072B50
  20. #include <core/std/memory.h>
  21. #include <boost/signals2/signal.hpp>
  22. namespace rainynite::core {
  23. class AbstractNotify {
  24. public:
  25. AbstractNotify() :
  26. changed_signal(),
  27. destroy_detector(make_shared<Null>())
  28. {}
  29. AbstractNotify(AbstractNotify const& /*other*/) :
  30. changed_signal(),
  31. destroy_detector(make_shared<Null>())
  32. {}
  33. public:
  34. /**
  35. * Function to be called when object has changed.
  36. */
  37. inline void changed() {
  38. changed_signal();
  39. }
  40. /**
  41. * Subscribe to this object changes
  42. */
  43. template <typename F>
  44. boost::signals2::connection subscribe(F f) {
  45. auto slot = decltype(changed_signal)::slot_type(f);
  46. slot.track_foreign(destroy_detector);
  47. return changed_signal.connect(slot);
  48. }
  49. private:
  50. /**
  51. * Signal to subscribe to this object's changes
  52. */
  53. boost::signals2::signal<void()> changed_signal;
  54. private:
  55. struct Null {};
  56. shared_ptr<Null> destroy_detector;
  57. };
  58. } // namespace rainynite::core
  59. #endif