fork download
  1. #include <iostream>
  2. #include <unordered_set>
  3.  
  4. template < typename T > struct magic
  5. {
  6. magic() { objects.insert( static_cast<T*>(this) ) ; }
  7. magic( const magic& ) : magic() {}
  8. magic( magic&& ) : magic() {}
  9. ~magic() { objects.erase( static_cast<T*>(this) ) ; }
  10.  
  11. template< typename FN > static void for_each_instance( FN fn )
  12. { for( T* p : objects ) fn(p) ; }
  13.  
  14. static std::unordered_set<T*> objects ;
  15. };
  16.  
  17. template < typename T > std::unordered_set<T*> magic<T>::objects ;
  18.  
  19. struct A : magic<A>
  20. {
  21. void foo( int i, char c )
  22. { std::cout << "A::foo( " << this << ", " << i << ", " << c << " )\n" ; }
  23. };
  24.  
  25. struct B : magic<B>
  26. {
  27. void bar( double d ) const
  28. { std::cout << "B::bar( " << this << ", " << d << " )\n" ; }
  29. };
  30.  
  31. int main()
  32. {
  33. A one ;
  34. B two ;
  35. {
  36. A three = one ;
  37. B b[2] ;
  38. A::for_each_instance( []( A* p ) { p->foo( 99, 'X' ) ; } ) ;
  39. B::for_each_instance( []( B* p ) { p->bar( 12.8 ) ; } ) ;
  40. }
  41. std::cout << "------------------------\n" ;
  42. A::for_each_instance( []( A* p ) { p->foo( -7, 'Y' ) ; } ) ;
  43. B::for_each_instance( []( B* p ) { p->bar( 123.45 ) ; } ) ;
  44. }
  45.  
Success #stdin #stdout 0s 2992KB
stdin
Standard input is empty
stdout
A::foo( 0xbfaa5073, 99, X )
A::foo( 0xbfaa5071, 99, X )
B::bar( 0xbfaa5077, 12.8 )
B::bar( 0xbfaa5076, 12.8 )
B::bar( 0xbfaa5072, 12.8 )
------------------------
A::foo( 0xbfaa5071, -7, Y )
B::bar( 0xbfaa5072, 123.45 )