property-like data members

spir denis.spir at gmail.com
Sun Jan 2 02:29:48 PST 2011


Hello,

Using properties allows travesting a method call into direct data access. What if the underlying member actually is plain data? Would it be possible to provide a real data member where the language expects a property (for instance as range empty & front properties)?
Is there any difficulty for the compiler to check whether a data member of the same name and correct type exists? To help it, we could mark said data member with an @property hint. For instance:

struct String {
    char[] cs;
    private uint index = 0;     // for traversal
    @property char front;
    @property bool empty;
    this (string characters) {
        this.cs = characters.dup;
        this.empty = (this.cs.length == 0);
        if (this.cs.length > 0)
            this.front = this.cs[0];
    }
    @property void popFront () {
        ++ this.index;
        this.empty = (this.index >= this.cs.length);
        if (this.index < this.cs.length)
            this.front = this.cs[this.index];
    }
}
unittest {
    auto s = String("abc");
    // works fine
    while (! s.empty) {
        auto c = s.front;
        write(c,' ');
        s.popFront;
    }
    writeln();
    // works not
//~     foreach (char c ; s) write(c,' ');
     writeln();
}

Here, popFront does not only advance, it correctly sets empty and front, so that a single method is needed. But the language expects a method-property (actually, it complains for missing opApply *).
I'm a bit troubled to implement methods where plain data does the job and conceptually better matches my model (maybe it's only me: I wish the code to mirror my views).

[Note: I do not mean at all the current imput-range model is overkill or anything similar. It is certainly more general as is, and I do not have enough various use cases to give any opinion on that! The given example is just that: an example.]

Denis

(*) Would be good to update the error message:
	Error: no property 'opApply' for type 'String'
	Error: opApply() function for String must return an int
-->
	Error: type String does not provide any iteration method.
-- -- -- -- -- -- --
vit esse estrany ☣

spir.wikidot.com



More information about the Digitalmars-d mailing list