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

12345swordy alexanderheistermann at gmail.com
Wed Jun 1 13:24:48 UTC 2022


On Wednesday, 1 June 2022 at 12:24:23 UTC, Dukc wrote:
> 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.
It is critical if you working with other people and you want the 
code to be self evident.

- Alex



More information about the Digitalmars-d mailing list