Add property-like Function to Type ?

Meta jared771 at gmail.com
Wed Apr 25 03:55:29 UTC 2018


On Tuesday, 24 April 2018 at 21:36:19 UTC, Rubn 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 don't control T and can't add members, then the best thing 
you can probably do is instead write T.init.sizeof32. Actually, 
though, you can be sneaky about it and use a local function to 
shadow Test, but this is probably more trouble than it's worth:

import std.stdio;

struct Test
{
}

@property sizeof32(Test t) { return 1; }

void main()
{
     @property Test() { return .Test.init; }
     writeln(Test.sizeof32);
}

This is really annoying, though, because you have to declare the 
Test function in every function or struct/class definition you 
use it in. You can create a mixin that does it automatically, but 
you'd still have to do `mixin(testProperties)` (where 
testProperties is an enum you've defined that's just the function 
definition).


More information about the Digitalmars-d-learn mailing list