Readonly-to-outside variable

Justin Whear via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Tue Apr 28 12:49:29 PDT 2015


On Tue, 28 Apr 2015 19:30:04 +0000, tcak wrote:

> Is there any way to define a variable or an attribute as read-only
> without defining a getter function/method for it?
> 
> Thoughts behind this question are:
> 1. For every reading, another function call process for CPU while it
> could directly read the value from memory.
> 
> 2. Repetition of same name for variable and getVariableName. (Some might
> not agree with this but I like the code when it looks nice.)

1. I wouldn't worry too much about the performance--compiling with gdc or 
ldc with inlining should reduce it to a simple access.
2. You can clean it up if it annoys you with something like this:

mixin template readonly(T, string name)
{
    mixin(`private T _`~name~`;T `~name~`()@property{return _`~name~`;}`);
}

Use it like:

class Foo
{
    // injects a private int _x, public int x()
    mixin readonly!(int, "x");
}


More information about the Digitalmars-d-learn mailing list