fork(1) download
  1. #include <iostream>
  2. #include <memory>
  3.  
  4. struct complex_struct
  5. {
  6. void (*doSmth)();
  7. };
  8.  
  9. struct complex_struct_handle
  10. {
  11. // functions
  12. virtual void doSmth() = 0;
  13. };
  14.  
  15. template<complex_struct* S>
  16. struct csh_imp : public complex_struct_handle
  17. {
  18. // implement function using S
  19. void doSmth()
  20. {
  21. // Optimization: simple pointer-to-member call,
  22. // instead of:
  23. // retrieve pointer-to-member, then call it.
  24. // And I think it can even be more optimized by the compiler.
  25. S->doSmth();
  26. }
  27. };
  28.  
  29. class test
  30. {
  31. public:
  32. /* This function is generated by some macros
  33.   The static variable is not made at class scope
  34.   because the initialization of static class variables
  35.   have to be done at namespace scope.
  36.  
  37.   IE:
  38.   class blah
  39.   {
  40.   SOME_MACRO(params)
  41.   };
  42.   instead of:
  43.   class blah
  44.   {
  45.   SOME_MACRO1(params)
  46.   };
  47.   SOME_MACRO2(blah,other_params);
  48.  
  49.   The pointer-to-data template parameter allows the variable
  50.   to be used outside of the function.
  51.   */
  52. std::auto_ptr<complex_struct_handle> getHandle() const
  53. {
  54. static complex_struct myStruct = { &test::print };
  55. return std::auto_ptr<complex_struct_handle>(new csh_imp<&myStruct>());
  56. }
  57. static void print()
  58. {
  59. std::cout << "print 42!\n";
  60. }
  61. };
  62.  
  63. int main()
  64. {
  65. test obj;
  66. obj.getHandle()->doSmth();
  67. }
Success #stdin #stdout 0.01s 2856KB
stdin
Standard input is empty
stdout
print 42!