Can I make a variable public and readonly (outside where was declared) at same time?
    Ali Çehreli via Digitalmars-d-learn 
    digitalmars-d-learn at puremagic.com
       
    Fri Sep 26 10:33:59 PDT 2014
    
    
  
On 09/26/2014 10:16 AM, AsmMan wrote:
 > I know I can combine it by making an extra variable plus a property like
 > this:
That's the proper way of doing it in D.
If it's too much work, it is possible to take advantage of mixins to 
reduce the boilerplate. I found the following code among my D samples; 
it must have been found on these forums.
Defining without "set" would disallow the setter:
     alias AutoImplementedProperty!(string, "get") title;
The code:
import std.stdio;
class Bar
{
     alias AutoImplementedProperty!(string, "get", "set") title;
}
template AutoImplementedProperty(T, args...)
{
     import std.typetuple;
     @property
     {
         private T _name;
         static if (args.length)
         {
             static if (staticIndexOf!("get", args) > -1)
             {
                 public T AutoImplementedProperty()
                 {
                     return _name;
                 }
             }
             static if (staticIndexOf!("set", args) > -1)
             {
                 public void AutoImplementedProperty(T value)
                 {
                     _name = value;
                 }
             }
         }
     }
}
void main(string[] args)
{
     Bar a = new Bar();
     a.title = "asf";
     writeln(a.title);
     return;
}
 > I wanted to do that without this a_ extra variable
If the value is set only once and it is known during construction, it is 
indeed mark the variable public const:
import std.stdio;
class Foo
{
     public const int a;
     this (int x)
     {
         a = 2 * x;
     }
}
void main()
{
     Foo f = new Foo(21);
     writeln(f.a); // output value of a
     Foo f2 = f;    // copy works
     f2 = f;        // assignment works
     // f.a = 10; // compile error: a is readonly outside Foo's methods.
}
Ali
    
    
More information about the Digitalmars-d-learn
mailing list