alias this
We have seen the individual meanings of the alias
and the this
keywords in previous chapters. These two keywords have a completely different meaning when used together as alias this
.
alias this
enables automatic type conversions (also known as implicit type conversions) of user-defined types. As we have seen in the Operator Overloading chapter, another way of providing type conversions for a type is by defining opCast
for that type. The difference is that, while opCast
is for explicit type conversions, alias this
is for automatic type conversions.
The keywords alias
and this
are written separately where the name of a member variable or a member function is specified between them:
alias member_variable_or_member_function this;
alias this
enables the specific conversion from the user-defined type to the type of that member. The value of the member becomes the resulting value of the conversion .
The following Fraction
example uses alias this
with a member function. The TeachingAssistant
example that is further below will use it with member variables.
Since the return type of value()
below is double
, the following alias this
enables automatic conversion of Fraction
objects to double
values:
import std.stdio; struct Fraction { long numerator; long denominator; double value() const { return double(numerator) / denominator; } alias value this; // ... } double calculate(double lhs, double rhs) { return 2 * lhs + rhs; } void main() { auto fraction = Fraction(1, 4); // meaning 1/4 writeln(calculate(fraction, 0.75)); }
value()
gets called automatically to produce a double
value when Fraction
objects appear in places where a double
value is expected. That is why the variable fraction
can be passed to calculate()
as an argument. value()
returns 0.25 as the value of 1/4 and the program prints the result of 2 * 0.25 + 0.75:
1.25