@property Incorrectly Implemented?

Timon Gehr via Digitalmars-d digitalmars-d at puremagic.com
Sun Sep 11 16:31:54 PDT 2016


On 11.09.2016 14:02, Ethan Watson wrote:
> On Sunday, 11 September 2016 at 07:19:54 UTC, John wrote:
>> ...
>> The part I'm asking to be changed, you probably didn't even ever use.
>> C# is a managed language, I don't think you can even take the pointer
>> of anything unless you enable the unsafe switch.
>
> ... In C#
> and in D, a property has *never* guaranteed the existence of a variable.
> In both cases, they allow syntactic sugar for letting the getter/setter
> pattern established by C++ look like variables.
> ...

His property returns by ref.


> ...
>
> Take std.bitmanip for an example of what I was talking about. It
> autogenerates properties for a bitfield. The types each property returns
> and lets you set are not at all indicative of the datatype underneath as
> it's literally just a bunch of bits. The property functions transform
> the data types given/return to/from a bitfield. What exactly do you
> suggest &property return if it was to return a char starting at bit 13
> of a bitfield?
> ...

Not a delegate. In a sane world, it would give you a compile error 
because 'property' is an rvalue.


> But we can go one further. __traits( allMembers, Type ) and __traits(
> getMember, Type ). Let's say you're writing an auto-serialisation
> library (or take std.json as an example). Assuming a property is a
> stand-in for another variable then what happens there when you're
> checking for the type of a member is the delegate type, and later on
> you'll get the actual variable. Now change it so that the type of a
> property returns the actual type. Now you're serialising a piece of data
> twice.
> ...

You do realize that typeof(property) is the type of the return value, 
right? Also, it's easy. Add __traits(isVariable,...) or 
__traits(isProperty,...), or just use .tupleof. Furthermore you can even 
get the property accessor function overload set using (a hypothetical) 
__traits(getPropertyAccessors,...).

> But what if our @property function increments another variable inside a
> class whenever you access it? That's pretty dangerous if you start
> treating the property as an actual type instead of a function/delegate.
>
> Thus, your example:
>
>     &t.x         // returns "ref int delegate()"
>     &t.x()       // ok returns "int*", but defeats purpose of @property
>     &(t.j = 10)  // shouldn't this return "ref int delegate(int)" ?
>
> First one I'd expect.

Why? It's awful.

> Second one I'd expect.

No, even more awful. typeof(t.x) is 'int'. You are not even supposed to 
be able to call an 'int'. The second one should be a compile error: 
"Error: function expected before (), not t.x of type int"

> Third one I'd expect results in int*.

Agreed, that one is sane.


More information about the Digitalmars-d mailing list