Should have @property

drug007 drug2004 at bk.ru
Mon Jan 16 10:37:08 UTC 2023


15.01.2023 18:54, Salih Dincer пишет:
> In the code snippet below should have @property. Otherwise, we get the 
> result this:
> 
>> 40
>> NP!(Foo!int)(opps!)
>> NP!(Foo!int)(opps!)
> 
> ```d
> struct NP(V) {
>    private V payload;
>    this(V x)
>    {
>      payload = x;
>    }
>    alias opCall this;
> 
>    @property: // <-- should be here
>    auto opCall() inout // ditto
>    {
>      return payload.value;
>    }
>    auto opCall(T)(T x)
>    {
>      return payload.value = x;
>    }
> }
> 
> class Foo(T)
> {
>    private T value;
>    NP!Foo wrapper;
> 
>    this()
>    {
>      wrapper = NP!Foo(this);
>    }
> 
>    override string toString()
>    {
>      return "opps!";
>    }
> }
> 
> import std.stdio;
> void main()
> {
>    auto foo = new Foo!int;
>    foo.value = 40;
> 
>    foo.value.writeln;   // 40
>    foo.wrapper.writeln; // 40
> 
>    foo.wrapper = 41;
>    foo.wrapper.writeln; // 41
> }
> ```
> SDB at 79

Yes, this is why I use @property despite advises to not use it. 
@property attribute makes your method be treated like a field, not as a 
method by returning the method calling result, not the method itself. So 
in you code if you use @property you get value, if you do not use it you 
get method. Another way is you can add handling for methods and return 
the method calling result yourself. But it's impossible in this case 
because it is handled by Phobos.


More information about the Digitalmars-d mailing list