Don't like ads? PRO users don't see any ads ;-)
Guest

Untitled

By: a guest on Aug 12th, 2012  |  syntax: None  |  size: 1.75 KB  |  hits: 8  |  expires: Never
download  |  raw  |  embed  |  report abuse  |  print
Text below is selected. Please press Ctrl+C to copy to your clipboard. (⌘+C on Mac)
  1. Python with statement in C  
  2. #include <iostream>
  3. #include <vector>
  4.  
  5. class With
  6. {
  7. public:
  8.     class A
  9.     {
  10.     public:
  11.         virtual ~A() { }
  12.     };
  13.  
  14.     template <typename T>
  15.     class B : public A
  16.     {
  17.     public:
  18.         B(T& _t) : t(_t)
  19.         {
  20.             t.bind();
  21.         }
  22.  
  23.         virtual ~B()
  24.         {
  25.             t.release();
  26.         }
  27.  
  28.         T& t;
  29.     };
  30.  
  31.     template <typename... Args>
  32.     With(Args&... args)
  33.     {
  34.         set(args...);
  35.     }
  36.  
  37.     ~With();
  38.  
  39.     template <typename T, typename... Args>
  40.     void set(T& t, Args&... args)
  41.     {
  42.         set(t);
  43.         set(args...);
  44.     }
  45.  
  46.     template <typename T>
  47.     void set(T& t)
  48.     {
  49.         a.push_back(dynamic_cast<A*>(new B<T>(t)));
  50.     }
  51.  
  52.     std::vector<A*> a;
  53. };
  54.        
  55. With::~With()
  56. {
  57.     for (auto it = a.begin(); it != a.end(); ++it)
  58.     {
  59.         delete *it;
  60.     }
  61. }
  62.        
  63. class X
  64. {
  65. public:
  66.     void bind() { std::cout << "bind x" << std::endl; }
  67.     void release() { std::cout << "release x" << std::endl; }
  68. };
  69.  
  70. class Y
  71. {
  72. public:
  73.     void bind() { std::cout << "bind y" << std::endl; }
  74.     void release() { std::cout << "release y" << std::endl; }
  75. };
  76.  
  77. int main()
  78. {
  79.     X y;
  80.     Y y;
  81.  
  82.     std::cout << "start" << std::endl;
  83.     {
  84.         With w(x, y);
  85.         std::cout << "with" << std::endl;
  86.     }
  87.  
  88.     std::cout << "done" << std::endl;
  89.  
  90.     return 0;
  91. }
  92.        
  93. template <typename T>
  94. class B {
  95. public:
  96.     B(T& _t) : t(_t){
  97.         t.bind();
  98.     }
  99.     ~B() {
  100.         t.release();
  101.     }
  102.     T& t;
  103. }
  104.        
  105. {
  106.     B<X> bound_x(x);  // x.bind is called
  107.     B<Y> bound_y(y);  // y.bind is called
  108.     // use x and y here
  109. } // bound_x and bound_y is destroyed here
  110.   // so x.release and y.release is called
  111.        
  112. struct X {
  113.     X() { std::cout << "bindn"; }
  114.     ~X() { std::cout << "releasen"; }
  115. };
  116. int main() {
  117.     X x;
  118. }