Thread overview
Type sniffing at runtime
May 16, 2020
n0den1te
May 16, 2020
Alex
May 16, 2020
Ali Çehreli
May 16, 2020
Hi,

    I am working through the book 'Programming in D' and wanted to take the sample program on http://ddili.org/ders/d.en/types.html, one step further:


    import std.stdio;

    void main() {
        writeln("Type           : ", int.stringof);
        writeln("Length in bytes: ", int.sizeof);
        writeln("Minimum value  : ", int.min);
        writeln("Maximum value  : ", int.max);
        writeln("Initial value  : ", int.init);
    }

Say, I want to have a list of types and sniff each type as I go: (this doesn't compile, yet)




    auto types = [bool, byte, ubyte, short, ushort, int, uint, long, ulong, float, double, real, char, wchar, dchar];

    for (t; types) {
        sniffType(t);
    }


    void sniffType(auto myType) {
        writeln('Type           : ', myType.stringof);
        writeln('Length in bytes: ', myType.sizeof);
        writeln('Minimum value  : ', myType.min);
        writeln('Maximum value  : ', myType.max);
        writeln('Initial value  : ', myType.init);wri
    }


How would I go about achieving this?

PS: Thanks for making this book online, Ali!
May 16, 2020
On Saturday, 16 May 2020 at 05:22:49 UTC, n0den1te wrote:
> [...]

For example, like this:

´´´
import std;

alias types = AliasSeq!(
    bool, byte, ubyte, short, ushort, int, uint, long, ulong, float, double, real, char, wchar, dchar
);

void main()
{
	static foreach(type; types)
    {
        sniffType!type;
    }
}


void sniffType(T)() {
    writeln("Type           : ", T.stringof);
    writeln("Length in bytes: ", T.sizeof);
    static if(__traits(compiles, T.min))
        writeln("Minimum value  : ", T.min);
    writeln("Maximum value  : ", T.max);
    writeln("Initial value  : ", T.init);
}

´´´

However, for the char, wchar and dchar types the results of min, max and init are somewhat cumbersome. And T.min does not compile for the floating point types.


May 16, 2020
On 5/15/20 11:12 PM, Alex wrote:

>      static if(__traits(compiles, T.min))
>          writeln("Minimum value  : ", T.min);

A little improvement:

    static if(__traits(isFloating, T)) {
      writeln("Minimum value  : ", -T.max);

    } else {
      writeln("Minimum value  : ", T.min);
    }

Ali