Metaprogramming in D : Some Real-world Examples
Denis Koroskin
2korden at gmail.com
Tue Nov 10 01:38:34 PST 2009
On Tue, 10 Nov 2009 03:27:20 +0300, Bill Baxter <wbaxter at gmail.com> wrote:
> On Mon, Nov 9, 2009 at 4:09 PM, Walter Bright
> <newshound1 at digitalmars.com> wrote:
>> Looks like Bill Baxter is giving a presentation on D Nov. 18!
>>
>> http://www.nwcpp.org/
>
> Yep, that's right, and I'd be quite grateful to you smart folks here
> if you could share your meta-programming favorites with me! If
> you've got a real-world example of meta-programming in D that you
> think is particularly handy, then please send it my way
>
> I'm looking for small-but-useful things that are easy to explain, and
> make something easier than it would be otherwise. Things like places
> where static if can save your butt, or loop unrolling, and passing
> code snippets to functions like in std.algorithm.
>
> Things like a compile-time raytracer or regexp parser (though quite
> cool!) are not what I'm after. Too involved for a short talk.
>
> --bb
kprintf (a printf variant) in XoMB is a nice example imo. It accepts
format as a template parameter, doing all the checks at compile-time (and
more).
http://github.com/xomboverlord/xomb-bare-bones/blob/6d924a9fd7cafe43aa50f38c0cd04c44187d4993/kernel/core/kprintf.d
/* This template will generate code for printing and will do
* all parsing of the format string at compile time
*
* USAGE:
* kprintf!("format string {specifier} ... ")(args...);
*
* EXAMPLES:
* kprintf!("Integer: {}")(10);
* kprintf!("{!cls}Cleared the screen.")();
* kprintf!("{!pos:2,3}At position (2,3)")();
* kprintf!("{!fg:LightBlue!bg:Gray}{}")(25);
* kprintf!("{!fg:Red}redness")();
* kprintf!("{x} Hex!")(145);
* kprintf!("Curly Brace: {{")();
*
* COMMANDS:
* !cls - Clears the screen.
* !fg - Sets the foreground color, see the Color enum
* in kernel/dev/console.d.
* !bg - Sets the background color, same as above.
* !pos - Moves the cursor to the x and y given, see example above.
*
* SPECIFIERS:
* {x} - Prints the hex value.
* {u} - Treats as unsigned.
* {} - Prints common form.
*
* WHY IS IT COOL?
* - Compile time parsing of format strings
* - Type checking at compile time as well
* - That means it can tell you that you are dumb before you execute.
* - No need to specify type information.
*
* - So we can do this and not care about the
* output of the function:
*
* auto blah = someFunction();
* kprintf!("Some Arbitrary Info: {}")(blah);
*
* WOWWY WOW WOW!
*
*/
More information about the Digitalmars-d-announce
mailing list