What is the state of @property?

Salih Dincer salihdb at hotmail.com
Fri Aug 26 09:12:49 UTC 2022


> On Thursday, 25 August 2022 at 14:49:51 UTC, Salih Dincer wrote:
> One benefit of @property is that it allows the compiler to 
> infer automatically.  So it behaves like auto but superior! For 
> example:

```d
import std.stdio,
        std.format : conv = format;

             //version = 1;
void main()
{
   char[6] text = "abcDEF".dup;
   auto VERSION = VerA!6(text); // sub-versions

   // range for sure (all version!)
   foreach(c; VERSION) c.write;
   "(empty == true)".writeln;

   // VerA.0, VerB.0: front() => D (one character)
   // VerA.1, VerB.1: toString() => abcDEF (all)
   //VERSION.writeln;/*

     VerA!6(text).writeln;
     VerB!6(text).writeln;
   //*/
}

struct VerA(int len)
{
   char[len] bytes;
   int index = len / 2;

   @property/*
   @system//*/
   {
     alias front this;

     bool empty() { return index == len; }
     char front() { return bytes[index]; }
     void popFront() { ++index; }
   }
   version(1) {
     string toString() { return conv("%s", bytes); }
   }
}

struct VerB(int len)
{
   char[len] bytes;
   int index = len / 2;

   alias front this;

   @property/*
   @system//*/
   {
     bool empty() { return index == len; }
     char front() { return bytes[index]; }
     void popFront() { ++index; }
   }
   version(1) {
     string toString() { return conv("%s", bytes); }
   }
}
```

I discovered another feature of @property while accessing it with 
writeln(). You need the alias and InputRange elements to see 
this...

Have I got it right? When accessing the structure with writeln(), 
if there is toString(), it is executed first, otherwise 
InputRange elements come into play. Just like we did with 
foreach().

If you scope the InputRange elements into the @property scope, 
the alias becomes priority. It's the opposite when you scope it 
to @system.

SDB at 79


More information about the Digitalmars-d mailing list