Special Type Challenge

via Digitalmars-d digitalmars-d at puremagic.com
Mon Feb 9 02:11:59 PST 2015


On Sunday, 8 February 2015 at 19:59:40 UTC, Meta wrote:
> On Sunday, 8 February 2015 at 13:06:08 UTC, Marc Schütz wrote:
>> No, `alias this` convert from the type it is declared in to 
>> another type. `opImplicitCast` would be declared in the 
>> destination type.
>
> So like this?
>
> struct Type1
> {
>     string str;
> }
>
> struct Type2
> {
>     string str;
>
>     Type2 opImplicitCast(Type1 t)
>     {
>         return Type2(t.str);
>     }
> }
>
> void main()
> {
>     Type2 t2 = Type1("Hello, World!");
> }
>
> Instead of the opposite?

Yes. It's almost like a constructor, but would be called wherever 
an explicit call to the constructor is required today:

     struct S {
         this(int x) {}
     }

     S test1() {
         return 10;    // not ok
         return S(10); // works
     }

     struct T {
         static typeof(this) opImplicitCast(int x) {
             return typeof(this)(x);
         }
     }

     T test1() {
         return 10;    // ok
         return T(10); // not sure whether this should
                       // work or not
     }

Because it's so similar to a constructor (it always needs to be 
static and return `typeof(this)`), maybe a special syntax can be 
used:

     struct S {
         @implicit this(int x) {}
     }


More information about the Digitalmars-d mailing list