Proper way to handle "alias this" deprecation for classes
Salih Dincer
salihdb at hotmail.com
Fri May 12 15:00:48 UTC 2023
On Sunday, 7 May 2023 at 21:04:05 UTC, Inkrementator wrote:
> Open question to everybody: What you're opinion on using opCast
> for this? Since it's a type conversion, it seems fitting to me.
Can't converting without explicitly specifying in D is a big
shortcoming in my opinion. There is such a thing as implicitly
convertion though, but it's very confusing. I don't see that
simplicity in C++ in the D codes!
```CPP
#include <iostream>
using namespace std;
struct Fraction {
int num, den;
Fraction(int n, int d) {
num = n;
den = d;
}
// Conversion operator: return float value of fraction
operator float() const
{
return float(num) / float(den);
}
};
int main()
{
Fraction f(2, 5);
float val = f;
cout << val << '\n'; // 0.4
return 0;
}
```
You should do the same in D like this:
```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);
}
}
import std.stdio;
int main()
{
auto f = Fraction(2, 5);
float val = cast(float)f;
val.writeln; //0.4
return 0;
}
```
SDB at 79
More information about the Digitalmars-d-learn
mailing list