TypeFunction example: ImplictConvTargets

Stefan Koch uplink.coder at googlemail.com
Wed Oct 7 22:31:52 UTC 2020


On Wednesday, 7 October 2020 at 01:27:17 UTC, claptrap wrote:
> 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.

Your code unfortunately won't work, because `= void`;
has special semantics, it won't assign the type void but leave 
the variable uninitialized.

This is what I wrote and it has shown me a bug.
alias variables should be initialized to an invalid type called, 
TError.
Inside the type-function implementation.
---
alias type = alias;

type biggestType(type[] types ...)
{
     type result;  // should initialize to Terror (The error type 
(the type that is not a type))
                   // for some reason initializes to alias now?
     foreach(t; types)
         if (t.sizeof > result.sizeof) result = t;
     return result;
}
// working around parser issues again.
// is expressions don't like function calls inside them ;)
alias I(alias A) = A;

pragma(msg, is(I!(biggestType()) == alias)); // prints true but 
really should not!
pragma(msg, is(I!(biggestType(int)) == int)); // prints true as 
it should
pragma(msg, is(I!(biggestType(int, ulong)) == int)); // prints 
false as it should
pragma(msg, is(I!(biggestType(int, ulong)) == ulong)); // prints 
true.




More information about the Digitalmars-d mailing list