Proper way to handle "alias this" deprecation for classes

Dom DiSc dominikus at scherkl.de
Wed May 17 08:00:17 UTC 2023


On Friday, 12 May 2023 at 15:00:48 UTC, Salih Dincer wrote:

> ```d
> struct Fraction {
> 	int num, den;
>
> 	this(int n, int d)
> 	{
> 		num = n;
> 		den = d;
> 	}
>
> 	// Cast Expression : convert float value of fraction
> 	auto opCast(T : float)() const
> 	{
> 		return cast(float)(num) / cast(float)(den);
> 	}
> }
> ```

If you want auto-conversion, you should be more explicit:
```d
float opCast() { }
```
because if you return "auto" it is not the highest-prio fit and 
therefore not chosen.
If you have multiple choices, you still don't need to use "auto". 
Instead you can return T:
```d
T opCast(T)() if(isFloatingPoint!T)
{
    return cast(T)num / cast(T)den; // float, double or real
}
```
Kind of ironic, but especially "auto" does NOT fit automatically 
:-)


More information about the Digitalmars-d-learn mailing list