fork download
  1. #include <iostream>
  2.  
  3. struct Settings
  4. {
  5. Settings(int v_) : v(v_) {}
  6. int v;
  7. };
  8.  
  9. //http://stackoverflow.com/a/11255852
  10. #define useHardwareWith(settings) \
  11. acquireHardware(settings); \
  12. for( \
  13.   struct \
  14.   { \
  15.   struct inner \
  16.   { \
  17.   inner() : done_(false) \
  18.   { \
  19.   } \
  20.   void run() \
  21.   { \
  22.   done_ = true; \
  23.   } \
  24.   ~inner() \
  25.   { \
  26.   releaseHardware(); \
  27.   } \
  28.   bool done_; \
  29.   }; \
  30.   bool done() const \
  31.   { \
  32.   return inner_.done_; \
  33.   } \
  34.   bool run() \
  35.   { \
  36.   inner_.done_ = true; \
  37.   } \
  38.   inner inner_; \
  39.   } magic; !magic.done() ; magic.run())
  40.  
  41. void acquireHardware(const Settings& settings)
  42. {
  43. std::cout << "acquire(" << settings.v << ")\n";
  44. }
  45.  
  46. void releaseHardware()
  47. {
  48. std::cout << "release()\n";
  49. }
  50.  
  51. void doHardwareStuff(const Settings& settings)
  52. {
  53. useHardwareWith(settings)
  54. {
  55. if (settings.v == 0)
  56. {
  57. std::cout << "side-exit\n";
  58. return;
  59. }
  60. std::cout << "Doing important hardware stuff\n";
  61. }
  62. }
  63.  
  64. int main()
  65. {
  66. Settings settings(0);
  67. doHardwareStuff(settings);
  68. doHardwareStuff(Settings(1));
  69. }
  70.  
Success #stdin #stdout 0s 3296KB
stdin
Standard input is empty
stdout
acquire(0)
side-exit
release()
acquire(1)
Doing important hardware stuff
release()