Proper way to handle "alias this" deprecation for classes

Ali Çehreli acehreli at yahoo.com
Sun May 7 18:19:04 UTC 2023


On 5/7/23 10:55, Chris Piker wrote:

 > According to dmd 2.103, alias this is
 > deprecated for classes, so I'd like to correct the problem.

alias this is for implicit type conversions, which can be achieved 
explicitly as well. Given the following old code:

class C {
     int* result;

     alias result this;
}

void foo(int*) {
}

auto main() {
     auto c = new C();

     // Implicit type conversion from C to int*:
     foo(c);
}

One can use a member function instead:

class C {
     int* result;

     auto asIntPtr() {
         return result;
     }
}

void foo(int*) {
}

auto main() {
     auto c = new C();

     // The same type conversion is now explicit:
     foo(c.asIntPtr);
}

Ali



More information about the Digitalmars-d-learn mailing list