Alias type with different initialiser.

John Colvin via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Mon Feb 13 14:59:11 PST 2017


On Monday, 13 February 2017 at 22:16:36 UTC, Bastiaan Veelo wrote:
> On Monday, 13 February 2017 at 16:40:02 UTC, Daniel Kozak wrote:
>> https://dlang.org/phobos/std_typecons.html#.Typedef
>
> Thanks for the pointers. Both Typedef and Proxy create types 
> that don't mix with the base type, which I want to the 
> contrary. So I guess I'll go with

Why not use a constructor instead of static opCall? Also, it's 
generally a bad idea to define `.init` for any type as code 
generally expects this to be the compiler-generated property 
(e.g. a value of type Initial!(int, 1) not of type int). So, 
perhaps like this:

struct Initial(T, T val)
{
     private T _payload = val;
     alias _payload this;
     this(T v)
     {
         _payload = v;
     }
     enum initial = val;
}

unittest
{
     alias Initial!(int, 1) int1;
     static assert(int1.initial == 1); // typeof(int1.initial) == 
int
     static assert(int1.init == 1); // typeof(int1.init) == 
typeof(int1)
     int1 i;
     assert(i == 1);
     int1 ii = 2;
     assert(ii == 2);
     assert(ii.init == 1);
     assert(int1.init == 1);

     void f(int val)
     {
         assert(val == 1);
     }
     f(i);

     int i0;
     assert(i0 == 0);
     i = i0;
     assert(i == 0);
     assert(i.init == 1);
     i0 = ii;
     assert(i0 == 2);
     assert(i0.init == 0);
}


More information about the Digitalmars-d-learn mailing list