TypeFunction example: ImplictConvTargets

Meta jared771 at gmail.com
Mon Oct 5 22:53:31 UTC 2020


On Monday, 5 October 2020 at 11:44:34 UTC, Stefan Koch wrote:
> Hi,
>
> I've posted an incomplete version of a semantic translation of 
> ImplictConvTargets from a template into a type function.
>
> After a few rather trivial fixes let me show you what the code 
> looks like now.
>
> ---
> alias type = alias;
>
> // needed to avoid deeper changes ... in the future it may be 
> unnecessary.
> auto makeAliasArray(type[] types ...)
> {
>     return types;
> }
>
> enum basic_types = makeAliasArray(bool, ubyte, char, byte, 
> ushort, wchar, short, uint, dchar, int, ulong, long);
>
> type[] convTargets(type T)
> {
>     if (isBasicType(T))
>         return basicTypeConvTargets(T);
>     return null;
> }
>
> bool isBasicType(type T)
> {
>     foreach(t;basic_types)
>     {
>         if (is(T == t))
>             return true;
>     }
>     return false;
> }
>
> type[] basicTypeConvTargets(type T)
> {
>     type[] targets;
>     targets.length = basic_types.length;
>     assert(isBasicType(T), "You may not call this function when 
> you don't have a basic type ... (given: " ~ T.stringof ~ ")");
>     size_t n = 0;
>     foreach(t;basic_types)
>     {
>         if (is(T : t))
>         {
>             targets[n++] = t;
>         }
>     }
>     return targets[0 .. n];
> }
> // 42 lines including whitespace and comments
>
> pragma(msg, convTargets(long)); // outputs [(ulong), (long)]

It would be very impressive if the following works:

type[] basicTypeConvTargets(type T)
{
     assert(isBasicType(T), "You may not call this function when 
you don't have a basic type ... (given: " ~ T.stringof ~ ")");
     return basic_types.filter!((alias U) => is(T: U)).array;
}

Yes, it instantiates a few templates, but it also demonstrates 
that working with type-values is as easy as working with regular 
values.


More information about the Digitalmars-d mailing list