Code repetition

IntegratedDimensions IntegratedDimensions at gmail.com
Sun May 27 06:47:38 UTC 2018


I have some code like

void foo()
{
     // setup stuff
     int x;
     scope(exit) something;

     //
     x = 34;
}

....


void foon()
{
     // setup stuff
     int x;
     scope(exit) something;

     //
}



All the setup stuff is virtually identical in each foo. There are 
slight differences such as a return value.


I would like to abstract the code code so that it can be handled 
in one place.

I have not found a way to do this in D. Template mixins do not 
work because of the arbitrary expressions. Putting the code in a 
template/function/lambda does not work because of the scopes 
which will be called when the main function exists.

A string mixin is too messy since it treats the code as a string 
losing all syntax highlighting, etc.

I'd love to have something like a template mixin where I can just 
do

mixin template fooSetup(ret)
{
     // setup stuff
     int x;
     scope(exit) something;

}


and

void foo()
{
    fooSetup(3);
}


void foo4()
{
    fooSetup(13);
}

and everything behave as it should. I'm guessing this is going to 
be impossible to achieve in D?



More information about the Digitalmars-d-learn mailing list