static map as a type function

Stefan Koch uplink.coder at googlemail.com
Wed Sep 23 09:46:54 UTC 2020


Hi guys,

So, today I wanted to implement handling of typesafe variadic 
array for type function (alias[] ...).
When writing a test for it I found out that I already did (on the 
talias_master branch which is different from talias_safe).

So here's the static map as a type function.
This also shows of interplay between templates and type functions.
That should be surprising since type functions are just regular 
functions that happen to accept types as arguments ;)

---

struct DummyType {} // just a dummy to get the right inference

auto getUDAs(alias T) { return __traits(getAttributes, T); } // 
needed because that's the shortest thing that'll return alias[]

alias alias_array = typeof(getUDAs(DummyType));

auto static_map_tf(alias F)(alias_array types ...)
{
     typeof(F(DummyType))[] result;
     result.length = types.length;

     foreach(i, t;types)
     {
         result[i] = F(t);
     }

     return result;
}

size_t sizeOf(alias t)
{
     return t.sizeof;
}

alias Int = int;
alias Ushort = ushort; // we need these aliases because the 
parser won't allow us to call a function with a reserved type 
identifier.

static assert(static_map_tf!sizeOf(Int, Ushort) == [4, 2]);

---

This code has been working quietly for a while.
So go and download 
https://github.com/UplinkCoder/dmd/tree/talias_master
Build your own compiler.
And play with type functions.

Cheers,

Stefan


More information about the Digitalmars-d mailing list