FunctionList.h 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. #pragma once
  2. /*
  3. * FunctionList.h, part of VCMI engine
  4. *
  5. * Authors: listed in file AUTHORS in main folder
  6. *
  7. * License: GNU General Public License v2.0 or later
  8. * Full text of license available in license.txt file, in main folder
  9. *
  10. */
  11. /// List of functions that share the same signature - can be used to call all of them easily
  12. template<typename Signature>
  13. class CFunctionList
  14. {
  15. public:
  16. std::vector<boost::function<Signature> > funcs;
  17. CFunctionList(int){};
  18. CFunctionList(){};
  19. template <typename Functor>
  20. CFunctionList(const Functor &f)
  21. {
  22. funcs.push_back(boost::function<Signature>(f));
  23. }
  24. CFunctionList(const boost::function<Signature> &first)
  25. {
  26. if (first)
  27. funcs.push_back(first);
  28. }
  29. CFunctionList(std::nullptr_t)
  30. {}
  31. CFunctionList & operator+=(const boost::function<Signature> &first)
  32. {
  33. funcs.push_back(first);
  34. return *this;
  35. }
  36. void add(const CFunctionList<Signature> &first)
  37. {
  38. for (size_t i = 0; i < first.funcs.size(); i++)
  39. {
  40. funcs.push_back(first.funcs[i]);
  41. }
  42. }
  43. void clear()
  44. {
  45. funcs.clear();
  46. }
  47. operator bool() const
  48. {
  49. return funcs.size();
  50. }
  51. void operator()() const
  52. {
  53. std::vector<boost::function<Signature> > funcs2 = funcs; //backup
  54. for(size_t i=0;i<funcs2.size(); ++i)
  55. {
  56. if (funcs2[i])
  57. funcs2[i]();
  58. }
  59. }
  60. template <typename Arg>
  61. void operator()(const Arg & a) const
  62. {
  63. std::vector<boost::function<Signature> > funcs2 = funcs; //backup
  64. for(int i=0;i<funcs2.size(); i++)
  65. {
  66. if (funcs2[i])
  67. funcs2[i](a);
  68. }
  69. }
  70. // Me wants variadic templates :(
  71. template <typename Arg1, typename Arg2>
  72. void operator()(Arg1 & a, Arg2 & b) const
  73. {
  74. std::vector<boost::function<Signature> > funcs2 = funcs; //backup
  75. for(int i=0;i<funcs2.size(); i++)
  76. {
  77. if (funcs2[i])
  78. funcs2[i](a, b);
  79. }
  80. }
  81. };