www.digitalmars.com         C & C++   DMDScript  

digitalmars.D - I just have to say that string mixins rock

reply Jonathan M Davis <jmdavisProg gmx.com> writes:
They've made my life way easier on a number of projects lately - particularly 
involving parsing. For instance, I've got some code for parsing H.264 headers 
that looks like this

mixin(parseUEV!("chroma_format_idc"));

if(chroma_format_idc == 3)
{
    mixin(parseU!("separate_colour_plane_flag", 1));
}

mixin(parseUEV!("bit_depth_luma_minus8"));
mixin(parseUEV!("bit_depth_chroma_minus8"));
mixin(parseU!("qpprime_y_zero_transform_bypass_flag", 1));
mixin(parseU!("seq_scaling_matrix_present_flag", 1));

I can simply pass a variable name as a string to a template (along with the 
number of bits to parse if relevant), and it'll generate a string that once 
mixed in will declare that variable, parse out bits from a buffer (with a name 
that the template knows) using whatever algorithm or function is associated 
with that template, and assign the result to that variable. And of course that 
variable is usable throughout the rest of the scope that the mixin was used 
in. On top of that, all I have to do is alter the few templates that I use to 
generate the strings, and I can make it print out the value, or append it to 
another buffer, or assign it to a corresponding field in a struct, so on and so 
forth. It saves quite a bit of code duplication, and makes it _really_ easy to 
change what a whole ton of lines of code do. And the code is just as efficient 
had I typed it all out myself, since it's just copy-pasted in place. This is 
fantastic!

I've got a variety of such mixins in a variety of projects, and they really 
help simplify the code. This is one feature in D that's really made my life 
easier. So, a huge thanks to whoever though it up (probably Walter, but I 
really don't know)!

- Jonathan M Davis
Jul 25 2012
parent reply Denis Shelomovskij <verylonglogin.reg gmail.com> writes:
That's why current `std.algorithm` string lambdas looks good and by 
design. I'm happy pull 707 is reverted.


-- 
Денис В. Шеломовский
Denis V. Shelomovskij
Jul 26 2012
parent Brad Anderson <eco gnuk.net> writes:
On Thu, Jul 26, 2012 at 4:25 AM, Denis Shelomovskij <
verylonglogin.reg gmail.com> wrote:

 That's why current `std.algorithm` string lambdas looks good and by
 design. I'm happy pull 707 is reverted.


 --
 =E4=C5=CE=C9=D3 =F7. =FB=C5=CC=CF=CD=CF=D7=D3=CB=C9=CA
 Denis V. Shelomovskij
I do like the brevity of the string lambdas but when I first started using D I was pretty confused by them. I'm torn. In any case, I probably won't be reopening the pull request until whatever bug in DMD that was causing the test failure is fixed and who knows when that will be. Regards, Brad Anderson
Jul 26 2012