Boost logo

Boost :

Subject: Re: [boost] [Utility] intuitive scoping with BOOST_WITH
From: Andrey Semashev (andrey.semashev_at_[hidden])
Date: 2015-08-07 05:07:06


On 07.08.2015 03:09, Marcel Ebmer wrote:
> Hi Everyone,
>
> What if you could do
>
> std::mutex the_mutex; using Lock = std::unique_lock<std::mutex>; void
> f() { with(Lock{the_mutex}) { do_something();
> do_other_thing(); } }
>
> *...or...*
>
> struct Pushed_matrix {
> Pushed_matrix() { glPushMatrix(); }
> ~Pushed_matrix() { glPopMatrix(); }
> };
>
> void f() {
> with(Pushed_matrix{})
> draw_something();
> }
>
> At C++Now (2015), I presented this idea of mine and a macro
> implementation (BOOST_WITH) in a lightning talk. Since reception was
> good and more serious than the talk itself, I continued to work on it. I
> would appreciate informal review and opinions:
>
> https://github.com/maysl/BOOST_WITH

I don't think this utility gives much compared to the naive macro-less
solution:

   f() {
     {
       Lock lock{the_mutex});
       do_something();
       do_other_thing();
     }
     do_something_without_a_lock();
   }

Also, your macro requires the type to be movable. This seems like a
rather strong requirement. For instance, it won't work with lock_guard.
If you really want to improve it you might want to use 'for' statement
instead of 'if', something along these lines:

   template< typename T >
   struct with_value
   {
     T value;
     bool guard;
   };

   #define BOOST_WITH(x)\
    for (with_value<decltype(x)> w{x, true}; w.guard; w.guard=false)

There is another limitation that is not so easy to lift - you cannot
access the guard value from within the scope. For instance, you cannot
use the lock to block on a condition variable.


Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk