title: Python with statement in C++
body: <p>I am trying to implement something similar to the <a href="http://docs.python.org/reference/compound_stmts.html#the-with-statement" rel="nofollow noreferrer">Python with statement</a> in C++. As I plan to use it mainly with Qt-OpenGL the methods are called <code>bind</code> and <code>release</code> (in Python <code>__enter__</code>, <code>__exit__</code>).</p>
  <p>Code I came up with:</p>
  <p>header:</p>
  <pre><code>#include &lt;iostream&gt;
  #include &lt;vector&gt;
  
  class With
  {
  public:
      class A
      {
      public:
          virtual ~A() { }
      };
  
      template &lt;typename T&gt;
      class B : public A
      {
      public:
          B(T&amp; _t) : t(_t)
          {
              t.bind();
          }
  
          virtual ~B()
          {
              t.release();
          }
  
          T&amp; t;
      };
  
      template &lt;typename... Args&gt;
      With(Args&amp;... args)
      {
          set(args...);
      }
  
      ~With();
  
      template &lt;typename T, typename... Args&gt;
      void set(T&amp; t, Args&amp;... args)
      {
          set(t);
          set(args...);
      }
  
      template &lt;typename T&gt;
      void set(T&amp; t)
      {
          a.push_back(dynamic_cast&lt;A*&gt;(new B&lt;T&gt;(t)));
      }
  
      std::vector&lt;A*&gt; a;
  };
  </code></pre>
  <p>cpp:</p>
  <pre><code>With::~With()
  {
      for (auto it = a.begin(); it != a.end(); ++it)
      {
          delete *it;
      }
  }
  </code></pre>
  <p>Usage:</p>
  <pre><code>class X
  {
  public:
      void bind() { std::cout &lt;&lt; &quot;bind x&quot; &lt;&lt; std::endl; }
      void release() { std::cout &lt;&lt; &quot;release x&quot; &lt;&lt; std::endl; }
  };
  
  class Y
  {
  public:
      void bind() { std::cout &lt;&lt; &quot;bind y&quot; &lt;&lt; std::endl; }
      void release() { std::cout &lt;&lt; &quot;release y&quot; &lt;&lt; std::endl; }
  };
  
  int main()
  {
      X y;
      Y y;
  
      std::cout &lt;&lt; &quot;start&quot; &lt;&lt; std::endl;
      {
          With w(x, y);
          std::cout &lt;&lt; &quot;with&quot; &lt;&lt; std::endl;
      }
  
      std::cout &lt;&lt; &quot;done&quot; &lt;&lt; std::endl;
  
      return 0;
  }
  </code></pre>
  <p>Questions:</p>
  <ol>
  <li>Needing <code>class A</code> and <code>class B</code> feels a bit clumsy. Is there a better alternative?</li>
  <li>Are there any draw backs in using <code>&amp;&amp;</code> instead of <code>&amp;</code>? It would make the usage of tempory objects possible (e.g. <code>With w(X(), y);</code>)</li>
  </ol>