Readonly-to-outside variable
Baz via Digitalmars-d-learn
digitalmars-d-learn at puremagic.com
Tue Apr 28 13:14:20 PDT 2015
On Tuesday, 28 April 2015 at 19:30:06 UTC, 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.)
an quick attempt:
---
union ReadOnlyOutside(T)
{
alias value this;
private T _value;
public const T value;
}
---
when you declare such a variable inside a struct or a class, the
code located in another module won't be able to modify the value:
module1:
---
struct Foo
{
ReadOnlyOutside!size_t roField;
}
---
module2:
void something(ref Foo foo)
{
writeln(foo.roField); // OK
writeln(foo.roField.value); // OK
foo.roField = 1; // FAIL
foo.roField.value = 1,// FAIL (because const).
foo.roField._value = 1,// FAIL (because not visible).
}
More information about the Digitalmars-d-learn
mailing list