Implicit type conversion depending on assignment

Salih Dincer salihdb at hotmail.com
Fri Mar 24 23:51:15 UTC 2023


On Thursday, 23 March 2023 at 13:38:51 UTC, Alexander Zhirov 
wrote:
> ```d
> struct MyVal
> {
>     string value;
>     // Here it would be possible to use an alias to this, but 
> it can only be used 1 time
> }
>
> auto a = MyVal("100");
> auto b = MyVal("11.2");
>
> int MyInt = a;        // Implicitly convert to target type
> float myFloat = b;    // Implicitly convert to target type
> ```

Have you tried using an associative array?

I feel that you will come up with a solution for your purpose 
from the examples below:

```d
template MyContainer(string data = "")
{       // Container name ---^
   struct Var
   {
     import std.variant;

     private Variant[string] values;
     alias values this;

     @property
     {
       Variant opDispatch(string key)() const
       {
         return values[key];
       }

       void opDispatch(string key, T)(T val)
       {
         values[key] = val;
       }
     }
   }

   static if(data.length > 0)
   {
     import std.format;

     mixin(data.format!"Var %s;");

   } else {

     Var data; // no conflicts

   }
}

import std.stdio;

void main()
{
   enum Tarih
   {
     AY  = 1,
     YIL = 2023
   }
   mixin MyContainer!"date";

   date.month = cast(ubyte)Tarih.AY;
   date.month.write("/");

   assert(date["month"] != Tarih.AY);
   assert(date["month"].type == typeid(ubyte));

   date.year = cast(short)Tarih.YIL;
   date.year.writeln(" in Turkish format");

   assert(date["year"] != Tarih.YIL);
   assert(date["year"].type == typeid(short));

   writefln("Date: %s/%s", date.year, date.month);
}
```

SDB at 79


More information about the Digitalmars-d-learn mailing list