Feature: `static cast`
Paul Backus
snarwin at gmail.com
Mon Jul 3 18:15:43 UTC 2023
On Monday, 3 July 2023 at 17:51:19 UTC, Nick Treleaven wrote:
> I tried but it doesn't seem to work:
>
> ```d
> class C
> {
> int* opCast(T)()
> if (is(T == void*)) => new int(42);
> }
>
> void main()
> {
> C c;
> auto p = cast(void*)c;
> pragma(msg, typeof(p)); // void*
> }
> ```
It calls `opCast`, and then implicitly converts the result from
`int*` to `void*`. You can see it if you add a side effect to
`opCast`:
```d
class C
{
int* opCast(T)()
if (is(T == void*))
{
import std.stdio;
writeln("Called opCast"); // will be printed
return new int(42);
}
}
```
And if you change `opCast` to return an incompatible type like
`int`, you will get a message about a failed implicit conversion:
```d
class C
{
int opCast(T)() if (is(T == void*)) => 42;
}
// Error: cannot implicitly convert expression
// `c.opCast()` of type `int` to `void*`
```
More information about the Digitalmars-d
mailing list