Idea: limited template expansion

Steven Schveighoffer via Digitalmars-d digitalmars-d at puremagic.com
Thu Jan 21 05:36:28 PST 2016


On 1/20/16 6:01 PM, David Nadlinger wrote:
> On Wednesday, 20 January 2016 at 22:00:45 UTC, Steven Schveighoffer wrote:
>> Imagine if you such a call returned something, and you simply used it
>> throughout the rest of your function. The compiler could rewrite this
>> as a template and compile all three versions and branch to the
>> appropriate one, but your code would simply read as a straightforward
>> procedural function.
>
> But if you abstract away the dispatch part into a (meta)template
> function like I suggested, the caller would still be just as linear, right?
>
> How would the client code be simpler with a built-in language feature?

The use case I have in mind is a parser, let's say an xml parser.

You have a file, it could be UTF8, UTF16, UTF32 (not to mention 
endianness, but that just adds to the number of finite possibilities)

Once you have determined the encoding, it doesn't change. So it's not 
advantageous to store the encoding in a runtime variable and check it at 
every turn. It makes more sense to templatize the code that deals with 
the XML parsing based on the code unit type, once that has been determined.

But client code ALSO has to deal with this, not just the library. So the 
implementation details sort of leak out into the caller.

Let's say there is a function parseXML that returns a range (a la 
byLine) that gives you elements from the xml tree.

Instead of a nice thing like:

foreach(element; file.asUTFX.parseXML)
{
    ... client code
}

you have to do something like this:

switch(file.detectBOM)
{
    case UTF8:
        foreach(element; file.asUTF8.parseXML)
        {
            ... client code
        }
        break;
    case UTF16:
        foreach(element; file.asUTF16.parseXML)
        {
            ... client code
        }
        break;
    case UTF32:
        foreach(element; file.asUTF32.parseXML)
        {
            ... client code
        }
        break;
}

In other words, the API *requires* you to write this switch thingy (and 
obviously to break up your client code into another function), or use 
some other mechanism. I want to hide the details of what is happening 
there in a simple call so the code is easy to read/write.

-Steve


More information about the Digitalmars-d mailing list