Struct with default ctor (Was: [dmd-beta] dmd 2.064 beta take 2)

Jacob Carlborg doob at me.com
Sun May 19 12:00:10 PDT 2013


On 2013-05-19 19:41, deadalnix wrote:

> I have bunch of code that goes like :
>
> auto oldVar = var;
> scope(exit) var = oldVar;
>
> This is begging for a RAII solution where I pass var as template
> parameter but would require default constructor. This is an actual
> problem I have right now as all save/restore are harder and harder to
> keep in sync for no reason and generate a lot of boilerplate.
>
> This is a problem I have right now that default constructor would solve,
> and this isn't the first time I hit that need.

You can do something like this:

void restore (alias value, alias dg) ()
{
     auto tmp = value;

     scope (exit)
         value = tmp;

     dg();
}

int a;

void foo () { a = 4 };

void main ()
{
     a = 3;
     restore!(a, {
         foo();
     });
}

The syntax isn't that pretty but it should work. I wish D had better 
syntax for this, something like:

restore(a) {
     foo();
}

-- 
/Jacob Carlborg


More information about the Digitalmars-d mailing list