compile-time detection of all pointer types in one test
Andy
andy.pj.hanson at gmail.com
Sun Jun 11 21:32:11 UTC 2023
On Sunday, 11 June 2023 at 21:25:21 UTC, DLearner wrote:
> Please consider:
> ```
> void main() {
>
> import std.stdio;
>
> struct foo {
>
> int foo1;
> char foo2;
> }
> foo* fooptr;
>
> void* genptr;
>
>
> static if (is(typeof(fooptr) == void*))
> writeln("fooptr is void*");
> else
> writeln("fooptr is not void*");
>
> static if (is(typeof(fooptr) == foo*))
> writeln("fooptr is foo*");
> else
> writeln("fooptr is not foo*");
>
> static if (is(typeof(genptr) == void*))
> writeln("genptr is void*");
> else
> writeln("genptr is not void*");
> }
> ```
> which produces:
> ```
> fooptr is not void*
> fooptr is foo*
> genptr is void*
> ```
>
> Since `void*` variables accept _all_ pointer types, I expected
> to see `fooptr is void*`.
>
> Is there any way of picking up, at compile-time, all pointer
> types in one test?
Use an `is` expression with a parameter list
(https://dlang.org/spec/expression.html#is-parameter-list):
void main() {
import std.stdio;
struct foo {}
foo* fooptr;
static if (is(typeof(fooptr) == T*, T))
writeln("fooptr is a pointer to a ", T.stringof);
else
writeln("fooptr is not a pointer");
}
As a bonus, you can make use of the pointee type `T`.
More information about the Digitalmars-d-learn
mailing list