FunctionList.h 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. /*
  2. * FunctionList.h, part of VCMI engine
  3. *
  4. * Authors: listed in file AUTHORS in main folder
  5. *
  6. * License: GNU General Public License v2.0 or later
  7. * Full text of license available in license.txt file, in main folder
  8. *
  9. */
  10. #pragma once
  11. VCMI_LIB_NAMESPACE_BEGIN
  12. /// List of functions that share the same signature - can be used to call all of them easily
  13. template<typename Signature>
  14. class CFunctionList
  15. {
  16. std::vector<std::function<Signature> > funcs;
  17. public:
  18. CFunctionList( std::nullptr_t ) { }
  19. CFunctionList( int ) { }
  20. CFunctionList( ){ }
  21. template <typename Functor>
  22. CFunctionList(const Functor &f)
  23. {
  24. funcs.push_back(std::function<Signature>(f));
  25. }
  26. CFunctionList(const std::function<Signature> &first)
  27. {
  28. if (first)
  29. funcs.push_back(first);
  30. }
  31. CFunctionList & operator+=(const CFunctionList<Signature> &first)
  32. {
  33. for( auto & fun : first.funcs)
  34. {
  35. funcs.push_back(fun);
  36. }
  37. return *this;
  38. }
  39. void clear()
  40. {
  41. funcs.clear();
  42. }
  43. operator bool() const
  44. {
  45. return !funcs.empty();
  46. }
  47. template <typename... Args>
  48. void operator()(Args ... args) const
  49. {
  50. std::vector<std::function<Signature> > funcs_copy = funcs;
  51. for( auto & fun : funcs_copy)
  52. {
  53. if (fun)
  54. fun(args...);
  55. }
  56. }
  57. };
  58. VCMI_LIB_NAMESPACE_END