fork download
  1. #include <functional>
  2. #include <iterator>
  3. #include <vector>
  4. #include <utility>
  5. #include <algorithm>
  6. #include <iostream>
  7. #include <typeinfo>
  8. #include <array>
  9.  
  10. std::vector<std::pair<std::function<void(int)>, void*>> callbacks;
  11.  
  12. class MyClass{
  13. static unsigned const num_possible_callbacks = 2; // keep updated
  14. std::array<std::type_info const*, num_possible_callbacks> _infos;
  15. unsigned _next_info;
  16.  
  17. // adds type_info and passes through
  18. template<class T>
  19. T const& add_info(T const& bound){
  20. if(_next_info == num_possible_callbacks)
  21. throw "oh shi...!"; // something went out of sync
  22. _infos[_next_info++] = &typeid(T);
  23. return bound;
  24. }
  25. public:
  26. MyClass() : _next_info(0){
  27. using std::placeholders::_1;
  28. callbacks.push_back(std::make_pair(
  29. add_info(std::bind(&MyClass::myFunc, this, _1)),
  30. (void*)this));
  31. callbacks.push_back(std::make_pair(
  32. add_info([this](int i){ return myOtherFunc(i, 0.5); }),
  33. (void*)this));
  34. }
  35.  
  36. ~MyClass(){
  37. using std::placeholders::_1;
  38.  
  39. callbacks.erase(std::remove_if(callbacks.begin(), callbacks.end(),
  40. [&](std::pair<std::function<void(int)>, void*> const& p) -> bool{
  41. if(p.second != (void*)this)
  42. return false;
  43. auto const& f = p.first;
  44. for(unsigned i = 0; i < _infos.size(); ++i)
  45. if(_infos[i] == &f.target_type())
  46. return true;
  47. return false;
  48. }), callbacks.end());
  49. }
  50.  
  51. void myFunc(int param){ /* ... */ }
  52. void myOtherFunc(int param1, double param2){ /* ... */ }
  53. };
  54.  
  55. int main(){
  56. auto print = []{ std::cout << "Callbacks:" << callbacks.size() << "\n"; };
  57. print();
  58. {
  59. MyClass c1;
  60. print();
  61. {
  62. MyClass c2;
  63. print();
  64. }
  65. print();
  66. }
  67. print();
  68. }
Success #stdin #stdout 0s 3068KB
stdin
Standard input is empty
stdout
Callbacks:0
Callbacks:2
Callbacks:4
Callbacks:2
Callbacks:0