D implicit conversion idiom

D strives to prevent implicit conversion between user defined types at all costs. This is mostly because there are so many implicit conversion rules in C++ and history has shown that implicit conversions can lead to really hard to track down bugs. But sometimes you still want a user defined type A to implicitly convert to a builtin type or user defined type B. This is possible in the D programming language using a property and the “alias this” feature.

The key to this idiom is the “convHelper” property. Which does the conversion and is callable without parentheses because it does not take any arguments (a property). Next we declare “alias convHelper this”. This causes the compiler to do a fallback to aliased symbol in case using the original type does not work. This way the compiler will automatically insert a call to convHelper in case our NumberAsString type can not be used directly. As a result we get our implicit conversion.

Unfortunately this does only work for a implicit conversion to a single type. Implicit conversions to multiple types are not possible because only a single alias this is allowed per type.

The code shown above has been tested with dmd 2.063.2