Template-based Preprocessing

Don Clugston dac at nospam.com.au
Sun Sep 3 23:50:26 PDT 2006


Garett Bass wrote:
> D's template mechanism is very promising, but I'm frequently frustrated 
> by the lack of C-preprocessor-equivalent power.  D templates currently 
> provide no means for insertion of arbitrarily parameterized blocks of 
> code, but I think they potentially could.
> 
> One feature I'm sorely missing that the C preprocessor happily provides 
> is the ability to insert blocks of code parameterized by an arbitrary 
> identifier, e.g.:
> 
> // C/C++
> #define SERIALIZABLE(type, identifier) \
>    type identifier;                   \
>                                       \
>    string serialize_##identifier() {  \
>        return toString(identifier);   \
>    }
> 
> class Foo {
>    SERIALIZABLE(int, i);
> };
> 
> Though this can't be reproduced by D templates, I'd like to suggest the 
> following:
> 
> // D (suggestion)
> template Serializable(T, token I) {
>    T I;
> 
>    string serialize_`I`() {
>        return toString(I);
>    }
> }
> 
> class Foo {
>    mixin Serializable!(int, i);
> }
> 
> Here I've used backticks to expand the identifier into code akin to the 
> C preprocessor's string-pasting operator (##).  I've included a keyword 
> "token" to mean something different from "alias", since it need not 
> specify an existing global identifier or alias.
> 
> I'm not really satisfied with this suggestion, maybe 
> C-preprocessor-style operators like # (stringizing) and ## 
> (string-pasting) would be more appropriate, and perhaps a different 
> keyword than "token".  I'm open to other ideas.

I've previously suggested the 'identifier' keyword for string pasting.
Stringizing is already possible, you can find the code for 
symbolnameof!() in dsource/ddl/meta, together with qualifiednameof!() 
which is significantly more powerful than anything in C++.
With identifier, you'd write:

string identifier("serialize_" ~ symbolnameof!(I))() {
   return toString(I);
}

> 
> I've not looked into the D front-end codebase yet, but I'm taking a 
> compilers class this semester, so I was hoping I might be able implement 
> this eventually.  Any ideas whether this is doable?  Any objections?
> 
> Regards,
> Garett



More information about the Digitalmars-d mailing list