static map as a type function

Stefan Koch uplink.coder at googlemail.com
Thu Sep 24 05:40:38 UTC 2020


On Thursday, 24 September 2020 at 05:13:49 UTC, Andrei 
Alexandrescu wrote:
> On 9/23/20 5:46 AM, Stefan Koch wrote:
>> 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]);
>
> Was looking at this example thinking, if only we had an object 
> available for each type. And then it struck me - we already do. 
> It's typeid. For each type T, typeid(T) yields an object (of 
> type class TypeInfo) that can be copied, compared etc.

Well yeah kindof.
What the type function does when it creates the alias from the 
type is indeed similar to what a complete type info would do.
However what you don't get is the nice syntax that come with type 
functions.
And you don't get the back-channel from type-info to type.

Getting typeinfo to properly fit in here, will likely mean 
internal compiler adjustments on the same scale as type functions.

There are also uses such as the type function for 
fullyQualifiedName which can't be done by converting to typeinfo 
objects.


More information about the Digitalmars-d mailing list