alias this of non-public member

Daniel Kozak via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Tue Apr 7 10:59:56 PDT 2015


On Tuesday, 7 April 2015 at 17:43:08 UTC, Daniel Kozak wrote:
> On Tuesday, 7 April 2015 at 17:21:09 UTC, Daniel Kozak wrote:
>>
>> On Tue, 07 Apr 2015 16:40:29 +0000
>> via Digitalmars-d-learn <digitalmars-d-learn at puremagic.com> 
>> wrote:
>>
>>> Hi!
>>> 
>>> Excuse me if this is obvious, but I can't recall coming 
>>> across anything similar and a quick search returns nothing 
>>> relevant:
>>> 
>>> struct Foo {
>>> }
>>> 
>>> struct FooWrapper {
>>>   alias x_ this;
>>>   private Foo* x_; // doesn't work, as x_ is private
>>> }
>>> 
>>> Basically, I want x_ to never be visible, except through the 
>>> "alias this" mechanism, at which point it should instead be 
>>> seen as public.
>>> 
>>> Assuming something like this is not already possible in a 
>>> clean way, I would like to suggest a tiny(I think) addition 
>>> to the language:
>>> 
>>> struct FooWrapper {
>>>   public alias x_ this; // overrides the visibility through 
>>> the alias;
>>>   private Foo* x_;
>>> }
>>> 
>>> 
>>> While I think this would be useful for the language, the 
>>> reason I want such a wrapper, is because I want to give 
>>> opIndex, toString, to a pointer, or, in fact just value 
>>> semantics, while keeping the rest of the interface through 
>>> the pointer.
>>> 
>>> I thought about using a class instead of a struct pointer, 
>>> but I am not sure about the memory layout for classes, nor 
>>> about the efficiency of overriding Object's methods, so I 
>>> didn't want to risk making it any less efficient. If someone 
>>> could shed some light about D's class memory layout and 
>>> general performance differences to a simple struct (or a C++ 
>>> class for that matter), that would also be great. In general, 
>>> more information about these sort of things would be great 
>>> for us also-C++ programmers. :)
>>
>> Works for me:
>>
>> struct M
>> {
>> 	void callMe() {
>> 		writeln("Ring...");
>> 	}
>> }
>>
>> struct S
>> {
>> 	alias m this;
>> 	private M m;
>> }
>>
>> void main(string[] args)
>> {
>> 	S s;
>> 	s.callMe();
>> }
>
> module some;
> import std.stdio;
>
> Another way is use template mixin:
>
> private mixin template M()
> {
> 	int someVar = 7;
> 	public void callMe() {
> 		writeln("Call");
> 	}
>
> 	public void callMe2() {
> 		writeln("Call2");
> 	}
> }
>
> struct S
> {
> 	mixin M;
> }
>
>
> ////
>
> module main;
> import some;
> void main(string[] args)
> {
> 	S s;
> 	s.callMe();
> 	s.callMe2();
> }

And maybe Proxy can be use for your use case:
http://dlang.org/phobos/std_typecons.html#.Proxy


More information about the Digitalmars-d-learn mailing list