www.digitalmars.com         C & C++   DMDScript  

digitalmars.D.learn - Type sniffing at runtime

reply n0den1te <somebody theinternet.village> writes:
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 15 2020
parent reply Alex <sascha.orlov gmail.com> writes:
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 15 2020
parent =?UTF-8?Q?Ali_=c3=87ehreli?= <acehreli yahoo.com> writes:
On 5/15/20 11:12 PM, Alex wrote:

  =C2=A0=C2=A0=C2=A0 static if(__traits(compiles, T.min))
  =C2=A0=C2=A0=C2=A0=C2=A0=C2=A0=C2=A0=C2=A0 writeln("Minimum value=C2=A0=
: ", T.min); A little improvement: static if(__traits(isFloating, T)) { writeln("Minimum value : ", -T.max); } else { writeln("Minimum value : ", T.min); } Ali
May 16 2020