I just have to say that string mixins rock
Jonathan M Davis
jmdavisProg at gmx.com
Wed Jul 25 23:24:54 PDT 2012
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
More information about the Digitalmars-d
mailing list