TypeFunction example: ImplictConvTargets

claptrap clap at trap.com
Wed Oct 7 01:27:17 UTC 2020


On Tuesday, 6 October 2020 at 23:27:10 UTC, Adam D. Ruppe wrote:
> On Tuesday, 6 October 2020 at 20:57:10 UTC, claptrap wrote:
>> Im less interested in performance than I am in being able to 
>> express what I want to do in clear concise code.
>
> Give me an example of what you'd like to use type functions for.
>
> I betcha I can adapt it to current D with very few changes.

I dont doubt it, but the question is could I do it? could a new D 
user do it?

IE. Whats the learning curve like?


> Take a look at this for example:
>
> ---
> import std.algorithm;
> template largestType(T...) {
>         auto get() {
>                 return reified!"a.sizeof".map!T
>                     .sort!((a, b) => a > b).front; // or 
> maxElement of course
>         }
>         alias largestType = T[get.idx];
> }
>
> pragma(msg, largestType!(long, int, real, byte)); // real

See the point is even even though I understand that, it took me a 
while to grep it, and I couldn't just rattle that off the top of 
my head, it'd take me a fair while to figure out how to do that. 
(Maybe i wouldn't even be able to on my own)

But with Type Functions it'd be something like this...

// assuming type is synonym for alias or whatever.

type convTargets(type[] args)
{
     assert(args.length > 0);
     type result = void; // IIRC void.sizeof == 1?
     foreach(t; args)
         if (t.size > result.sizeof) result = t;
     return result;
}

The point is TF are obvious, if you know regular D code, you can 
use type functions. I've got the gist of it from a handful of 
forums posts. The cognitive load is so much lower.




More information about the Digitalmars-d mailing list