fork download
  1. #include <iostream>
  2. #include <memory>
  3. #include <vector>
  4.  
  5. using namespace std;
  6.  
  7.  
  8. /////////////////////////////////////////
  9. // opengl_helper.h
  10. // this is some manager class that knows what should be initialized later
  11. struct OpenGLHelper
  12. {
  13. typedef std::function<void()> function_type;
  14.  
  15. static std::vector<function_type>& get_initialization_list();
  16.  
  17. static void register_initializer(function_type fn);
  18.  
  19. static void run_init();
  20. };
  21. // helper class that will register some function at construction time
  22. struct OpenGLHelper_initializer
  23. {
  24. OpenGLHelper_initializer(OpenGLHelper::function_type fn)
  25. {
  26. OpenGLHelper::register_initializer(fn);
  27. }
  28. };
  29. /////////////////////////////////////////
  30. //opengl_helper.cpp
  31.  
  32. std::vector<OpenGLHelper::function_type>& OpenGLHelper::get_initialization_list()
  33. {
  34. static std::vector<function_type> initializer_list;
  35. return initializer_list;
  36. }
  37.  
  38. // function that puts initializer into a list.
  39. void OpenGLHelper::register_initializer(OpenGLHelper::function_type fn)
  40. {
  41.  
  42. get_initialization_list().push_back(fn);
  43. }
  44.  
  45. void OpenGLHelper::run_init()
  46. {
  47. for (auto fn : get_initialization_list())
  48. fn();
  49. }
  50.  
  51. /////////////////////////////////////////
  52. // figure.h
  53. // here is sample class that will be registered for initialization
  54. struct Square
  55. {
  56. static int to_be_initialized;
  57.  
  58. // static member that will register Square class to be initialized
  59. static OpenGLHelper_initializer __initializer;
  60. };
  61.  
  62. /////////////////////////////////////////
  63. // Square.cpp
  64. int Square::to_be_initialized = 0;
  65. // this is the most interesting part - register square into initializer list
  66. OpenGLHelper_initializer Square::__initializer([](){
  67. Square::to_be_initialized = 15;
  68. std::cout << "Called Square::init: " << to_be_initialized << std::endl;
  69. });
  70.  
  71. int main()
  72. {
  73. std::cout << "Before initialization : " << Square::to_be_initialized << std::endl;
  74. OpenGLHelper::run_init();
  75. std::cout << "After initialization : " << Square::to_be_initialized << std::endl;
  76. return 0;
  77. }
Success #stdin #stdout 0s 3472KB
stdin
Standard input is empty
stdout
Before initialization : 0
Called Square::init: 15
After  initialization : 15