title: Best practices + syntax for implementing a "contextmanager" in C++
body: <p>Our Python codebase has metrics-related code that looks like this:</p>
  
  <pre><code>class Timer:
      def __enter__(self, name):
          self.name = name
          self.start = time.time()
  
      def __exit__(self):
          elapsed = time.time() - self.start
          log.info('%s took %f seconds' % (self.name, elapsed))
  
  ...
  
  with Timer('foo'):
      do some work
  
  with Timer('bar') as named_timer:
      do some work
      named_timer.some_mutative_method()
      do some more work
  </code></pre>
  
  <p>In Python's terminology, the timer is a <em>contextmanager</em>.</p>
  
  <p>Now we want to implement the same thing in C++, with an equally nice syntax. Unfortunately, C++ doesn't have <code>with</code>. So the "obvious" idiom would be (classical RAII)</p>
  
  <pre><code>class Timer {
      Timer(std::string name) : name_(std::move(name)) {}
      ~Timer() { /* ... */ }
  };
  
  if (true) {
      Timer t("foo");
      do some work
  }
  if (true) {
      Timer named_timer("bar");
      do some work
      named_timer.some_mutative_method();
      do some more work
  }
  </code></pre>
  
  <p>But this is extremely ugly syntactic salt: it's many lines longer than it needs to be, we had to introduce a name <code>t</code> for our "unnamed" timer (and the code breaks silently if we forget that name)... it's just ugly.</p>
  
  <p><strong>What are some syntactic idioms that people have used to deal with "contextmanagers" in C++?</strong></p>
  
  <hr>
  
  <p>I've thought of this abusive idea, which reduces the line-count but doesn't get rid of the name <code>t</code>:</p>
  
  <pre><code>// give Timer an implicit always-true conversion to bool
  if (auto t = Timer("foo")) {
      do some work
  }
  </code></pre>
  
  <p>Or this architectural monstrosity, which I don't even trust <em>myself</em> to use correctly:</p>
  
  <pre><code>Timer("foo", [&amp;](auto&amp;) {
      do some work
  });
  Timer("bar", [&amp;](auto&amp; named_timer) {
      do some work
      named_timer.some_mutative_method();
      do some more work
  });
  </code></pre>
  
  <p>where the constructor of <code>Timer</code> actually invokes the given lambda (with argument <code>*this</code>) and does the logging all in one go.</p>
  
  <p>Neither of those ideas seems like a "best practice", though. Help me out here!</p>
  
  <hr>
  
  <p>Another way to phrase the question might be: If you were designing <code>std::lock_guard</code> from scratch, how would you do it so as to eliminate as much boilerplate as possible?  <code>lock_guard</code> is a perfect example of a contextmanager: it's a utility, it's intrinsically RAII, and you hardly ever want to bother naming it.</p>