Using closure in function scope to make "real" private class members

Dukc ajieskola at gmail.com
Wed Jun 1 12:24:23 UTC 2022


On Wednesday, 1 June 2022 at 01:54:52 UTC, H. S. Teoh wrote:
> So today, I thought I wanted to explore how far I can push the 
> idea of using closures over local variables in function scope 
> to simulate class-private field, i.e.:
>
> --------
> auto makeObj() {
> 	int realPrivateX;
> 	class C {
> 		int modulePrivateX;
> 		void func() {
> 			realPrivateX++;
> 		}
> 	}
> 	return new C;
> }
> void main() {
> 	auto obj = makeObj();
> 	obj.modulePrivateX++; // OK
> 	obj.realPrivateX++; // NG
> }
> --------

Frankly, I don't think this thing is worth doing any hacks for. 
Controlling the scope of encapsulation is rarely that critical, 
and if it is, it's easier to just put the class to it's own file.


More information about the Digitalmars-d mailing list