fork download
  1. #include <iostream>
  2. #include <unordered_set>
  3.  
  4. template < typename T > struct magic
  5. {
  6. magic() : enable_for_each_instance(false) {}
  7.  
  8. magic( bool b) : enable_for_each_instance(b)
  9. { if(b) objects.insert( static_cast<T*>(this) ) ; }
  10.  
  11. magic( const magic& that ) : magic(that.enable_for_each_instance) {}
  12.  
  13. magic( magic&& that ) : magic(that.enable_for_each_instance) {}
  14.  
  15. ~magic() { if(enable_for_each_instance) objects.erase( static_cast<T*>(this) ) ; }
  16.  
  17. template< typename FN > static void for_each_instance( FN fn )
  18. { for( T* p : objects ) fn(p) ; }
  19.  
  20. const bool enable_for_each_instance ;
  21. private: static std::unordered_set<T*> objects ;
  22. };
  23.  
  24. template < typename T > std::unordered_set<T*> magic<T>::objects ;
  25.  
  26. struct A : magic<A>
  27. {
  28. explicit A( bool enable_magic = false ) : magic<A>(enable_magic) {}
  29. void foo( int i, char c )
  30. { std::cout << "A::foo( " << this << ", " << i << ", " << c << " )\n" ; }
  31. };
  32.  
  33. struct B : magic<B>
  34. {
  35. explicit B( bool enable_magic = false ) : magic<B>(enable_magic) {}
  36. void bar( double d ) const
  37. { std::cout << "B::bar( " << this << ", " << d << " )\n" ; }
  38. };
  39.  
  40. int main()
  41. {
  42. A one(true), x ;
  43. B two(true), y ;
  44. {
  45. A three = one ;
  46. B four, five = two ;
  47. A a[1000] ;
  48. B b[25] ;
  49. A::for_each_instance( []( A* p ) { p->foo( 99, 'X' ) ; } ) ;
  50. B::for_each_instance( []( B* p ) { p->bar( 12.8 ) ; } ) ;
  51. }
  52. std::cout << "------------------------\n" ;
  53. A::for_each_instance( []( A* p ) { p->foo( -7, 'Y' ) ; } ) ;
  54. B::for_each_instance( []( B* p ) { p->bar( 123.45 ) ; } ) ;
  55. }
  56.  
Success #stdin #stdout 0s 3036KB
stdin
Standard input is empty
stdout
A::foo( 0xbfbc3944, 99, X )
A::foo( 0xbfbc3940, 99, X )
B::bar( 0xbfbc3946, 12.8 )
B::bar( 0xbfbc3942, 12.8 )
------------------------
A::foo( 0xbfbc3940, -7, Y )
B::bar( 0xbfbc3942, 123.45 )