PHP-style (embedded variables) print statements

Don Clugston dac at nospam.com.au
Thu May 31 00:24:59 PDT 2007


With CTFE and text mixins, it is now reasonably straightforward to 
implement PHP-style 'dollar' embedded variables, in a type-safe manner.

For example, the attached code (rough draft) allows you to write things 
like:

int i;
const k = 8;
char [] str;
mixin(dprint("current=$i next=$(i+1) const=$(k*3) $str\n"));

which is typesafe, converts all compile-time constants directly into the 
format string, and converts everything else into a simple printf() call. 
The mixin line above becomes

printf("current=%d next=%d const=24 %.*s\n", i, i+1, str);

Note that unlike a tuple solution, it does not cause any template bloat.
Also doesn't have some of writefln's pitfalls (the case where a string 
contains a % character).

Incidentally, this could do a lot better than printf, because it could 
categorise the expressions. Eg, if there are no floating point 
variables, it could translate it to a simple print function which 
doesn't have the FP conversion code. Ditto for outputting arrays and 
objects. Other optimisations are possible - eg, it could also estimate 
how much buffer space is going to be required.

Downsides:
(1) need to use "mixin()" until we get macros.
(2) doesn't look like anything that's in D right now.
(3) how are IDE's going to know when a string contains embedded variables?

Opinions? Is something like this worth considering as an alternative to 
writefln, and to Tango's C# formatting and whisper syntax?

-------------- next part --------------
An embedded and charset-unspecified text was scrubbed...
Name: Dprint.d
URL: <http://lists.puremagic.com/pipermail/digitalmars-d/attachments/20070531/b8ae17f6/attachment.ksh>


More information about the Digitalmars-d mailing list