Read-only property without @property
Daniel N via Digitalmars-d
digitalmars-d at puremagic.com
Fri Sep 26 20:56:44 PDT 2014
On Friday, 26 September 2014 at 19:47:15 UTC, Steven
Schveighoffer wrote:
> I wanted to bring this over from D.learn, because I've never
> seen this before, and it's an interesting solution to creating
> a property without much boilerplate.
>
> So here it is:
>
> class Foo
> {
> union
> {
> private int _a; // accessible only in this module
> public const int a; // accessible from anywhere, but read
> only
> }
> }
>
> And it works now, probably has for a while.
>
> Thoughts? This can easily be boilerplated in something like
> roprop!(int, "a")
>
> I am really not sure what union does to compiler optimization
> or runtime concerns, if it has any significant drawbacks. From
> what I can tell, it's a valid solution.
>
> Credit to Mark Schütz for the idea.
>
> -Steve
Thanks, I love this!
There is actually a very important ABI difference, in all other
"property" implementations in other languages(of which I'm
aware), the ABI is changed to be a method rather than a member,
for this reason I think we shouldn't refer to this feature as a
"property", maybe "field/member" is more appropriate?
Both properties and "access restricted fields" has their place
depending on what one is trying to accomplish, but in most cases
I find myself wanting this very feature and not normal properties.
I couldn't resist trying this in C++, clang rejected it outright,
GCC let it through with a warning.
More information about the Digitalmars-d
mailing list