Add property-like Function to Type ?

Jonathan M Davis newsgroup.d at jmdavisprog.com
Tue Apr 24 21:52:42 UTC 2018


On Tuesday, April 24, 2018 21:36:19 Rubn via Digitalmars-d-learn wrote:
> I was wondering if I could create my own property in a way that
> can be used the same way as something like "T.sizeof". Right now
> I have the following to replace length:
>
> uint length32(T)(T[] array)
> {
>      return cast(uint)array.length;
> }
>
> I want something similar to be able to do the following:
>
>
> uint size = T.sizeof32;
>
> The closest I can think of is doing:
>
> uint size = sizeof32!T
>
>
> That's the best I can do, which is fine but I was wondering if
> there's any other way around that?

If you're dealing with a user-defined type, you can declare an enum or
static function on it to do something like T.sizeof32. However, you can't
add stuff like that without editing the type itself, so it won't work with
any types that you aren't defining yourself - especially built-in types.

If you're willing to use an instance of the type, then you can declare a
free function and use UFCS, but as soon as you want to use the type itself,
you're going to need to use a template, which means something like
sizeof32!T rather than T.sizeof32.

- Jonathan M Davis



More information about the Digitalmars-d-learn mailing list