www.digitalmars.com         C & C++   DMDScript  

digitalmars.D - Need help with accessing outer object

reply Cherry <cherry blossom.com> writes:
Greetings All

Can you help me with this code? I could not find any traits or 
other way to get me outer object of a given inner object. As for 
the context, I am fiddling with D trying to write a (domain 
specific) generic baseclass library. InnerBase is part of the 
library I write and the end user would be coding Outer and Inner 
classes. I do not want to force him to write getOuter kind of 
function. I would prefer not to ask him to add a mixin as well.

Is that possible, or is forcing the user to add a mixin the only 
way out?

Regards
- Cherry

////////////////////////////////////////////////////

class InnerBase{}
class Outer {
   class Inner: InnerBase {}
}
void main() {
   Outer outer = new Outer;
   auto inner = outer.new Outer.Inner();
   foo(inner);
}
void foo(T)(T t) {
   // somehow access inner.outer -- inner -> this.outer
   // Can not change Inner class to introduce getOuter 
functionality
   // I have access to InnerBase though and can add code there
}
Aug 29 2016
next sibling parent Cherry <cherry blossom.com> writes:
How about having traits like hasOuter and getOuter (analogous to 
hasMember and getMember)?

I can give it a shot to add these traits to D compiler. But would 
such a pull request be accepted? I mean of course the code in the 
pull-request has to meet review expectations, but would such a PR 
be accepted from required feature perspective?
Aug 29 2016
prev sibling next sibling parent Jacob Carlborg <doob me.com> writes:
On 2016-08-30 04:43, Cherry wrote:
 Greetings All

 Can you help me with this code? I could not find any traits or other way
 to get me outer object of a given inner object.
Use the ".outer" property [1]. [1] http://dlang.org/spec/class.html#nested -- /Jacob Carlborg
Aug 30 2016
prev sibling parent deed <none none.none> writes:
On Tuesday, 30 August 2016 at 02:43:16 UTC, Cherry wrote:

 Can you help me with this code?
class InnerBase { int a = 1; } class Outer { int b = 2; class Inner: InnerBase { int c = 3; } } void main() { Outer outer = new Outer; auto inner = outer.new Outer.Inner(); foo(inner); } void foo (T) (T t) { import std.stdio : writeln; writeln(t.a); // prints 1 writeln(t.outer.b); // prints 2 writeln(t.c); // prints 3 } dmd v2.071.2-b2 This should be posted in Learn at http://forum.dlang.org/group/learn
Aug 30 2016