Templates considered impressive

Salih Dincer salihdb at hotmail.com
Tue Oct 1 16:18:17 UTC 2024


On Tuesday, 1 October 2024 at 01:00:08 UTC, Andy Valencia wrote:
> ... A conversion like:
>
>     auto d = atoi!double("123.456");
>
> is about 4k of code.  Nice!
>

Congratulations on your initiative. D is very flexible with 
templates, especially with the mixin templates. For example, you 
might like this one:

```d
template MyCon (T, string str = "0")
{
     MyCon init = str;

     struct MyCon
     {
         string input;
         T value;

         this(string data)
         {
             import std.conv : to;
             value = data.to!T;
             input = data;
         }

         string toString() => input;

         string convertToHex()
         {
             import std.string : format;
             return input.format!"%-(%02X%)";
         }
     }
}


import std.stdio;
void main()
{
     //mixin MyCon!int;/*
     mixin MyCon!int zero;

     // There is an invisible object here: init (struct MyCon)
     zero.init.writeln;  //* 0 */

     // Here is a new object:
     MyCon!double num1 = "3.14";

     num1.writeln; // 3.14
     assert(num1.value == 3.14);

     // and a convenience function... :)
     num1.convertToHex.writeln;
     assert(num1.convertToHex == "332E3134");
}
```

SDB at 79


More information about the Digitalmars-d-learn mailing list