Template-based Preprocessing

Garett Bass garettbass at studiotekne.com
Sun Sep 3 13:38:53 PDT 2006


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 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