Class views - a new concept
Arafel
er.krali at gmail.com
Mon Jun 27 14:45:50 UTC 2022
On 27/6/22 1:33, forkit wrote:
> So I came up with this idea, based on discussion in another, rather
> controverial, thread ;-)
>
> In any case, I think this idea deserves it's own thread.
>
> NOTE::it's just an idea, and certainly **not** a proposal.
>
> I'd be interested to know, if anyone else out there knows of any
> langauge, where a concept like this has been implemented (i.e. a way to
> restrict specific class member functions to specific class variables).
>
> So...here I introduce a new concept, which (for now), we'll call a 'view'.
>
> It can solve multiple problems, at least for me.
>
> First, it eliminates a need for that very controversial idea of
> 'private(this)'
>
> Second, it allows fine grained control of member access, to member
> variables.
>
> Anything declared private, in a view, is simply private to that view.
>
There are probably some corner cases not covered, and I can't say how it
will perform... but it should be already possible to get something
really close and usable in most sensible cases:
```d
import std.typecons : Typedef;
class C {
/* static */ struct View { // Can and should be static if it doesn't
access any of C's internals
// What everything not in this View must use
public auto i() { return _i; }
public auto i(int i) { _i = i; }
// Internals not exposed anywhere else
private int _i;
};
// The magic bit
private Typedef!View _view;
// Could be automated and probably improved with some Proxy-like
meta-magic
public auto ref i(Args...)(Args args) { return _view.i(args); }
// Also something like this could perhaps be made to work:
// alias i = view.i
this() {
i = 1; // Works
_view.i = 2; // Works, but why would you use it?
// view._i = 3 // Fails
}
}
// Inheritance works as you'd expect
class D : C { }
void main() {
C c = new C();
c.i = 4; // Works
c._view.i = 5; // Works, but why would you use it?
// c.view._i = 6; // Fails
D d = new D();
d.i = 7 // Works, etc.;
}
```
More information about the Digitalmars-d
mailing list