Idea: limited template expansion

Steven Schveighoffer via Digitalmars-d digitalmars-d at puremagic.com
Wed Jan 20 13:27:15 PST 2016


I am writing some code for a library, and an interesting situation comes 
up. Let's say you have some code that can deal with wchar, dchar, or 
char arrays. You template the code based on the code unit type, but the 
input comes in as a file stream (which is bytes).

What I have been doing is this:

void foo(C)(C[] buf) {...}


ubyte[] buffer = ...;
switch(detectBOM(buffer))
{
   case UTF8:
      foo(cast(char[])buffer);
      break;
   case UTF16:
      foo(cast(wchar[])buffer);
      break;
   case UTF32:
      foo(cast(dchar[])buffer);
      break;
   default:
      assert(0);
}

Essentially, I'm wrapping a runtime check into a compile-time construct, 
but I have to always deal with this switch mechanism and a lot of boiler 
plate.

It would be cool if the compiler could "expand" a finitely instantiable 
template (one with a finite number of ways it can be instantiated) based 
on a runtime value, and do the switch for me.

Something like:

void foo(BOM b)(ubyte[] buffer) { ... /* cast to correct char type */ }

ubyte[] buffer = ...;
foo!(detectBOM(buffer))(buffer);

would expand into what I wrote manually. It may need a different syntax 
from template instantiation, since it does involve runtime checking.

Does this have any appeal to people? Any other use cases?

-Steve


More information about the Digitalmars-d mailing list