Nested Structs

js.mdnq js_adddot+mdng at gmail.com
Tue Dec 11 23:42:55 PST 2012


The follow code demonstrates a solution to the nested structs. It 
is far from optimal but maybe it is possible to use as a base 
solution:

http://dpaste.dzfl.pl/7f086694

What the code demonstrates is that a nested struct can use the 
parent class(or struct) without having to store a reference to 
it. This, then, does not waste space to store a reference that is 
not needed.

The issue is we must hard code the offsets of the struct objects 
inside the class(something the compiler already knows). Any 
modification of the class will require changing the values.

In fact, the compiler could do all the dirty work behind the 
scenes pretty efficiently(all compile time offset computation) 
and not require a templated struct(which seems to slow down the 
compilation of the program significantly... unless my computer is 
acting up).

In any case, the code is a first step. The next being computing 
the offsets of the structs automatically which will give a useful 
method of solving the problem until, hopefully, something is 
implemented directly in the compiler.














Code:

module main;

import std.stdio;

class A {
	A a;

	struct B(int ofs)  {
		int Value;
		A Parent()
		{
			auto p = cast(void *)&this - ofs;
			return cast(A)(p);
		}		
	}

	B!(12) b1;
	B!(12 + 4) b2;
	string Name;

	this()
	{
		Name = "Class";
		a = this;

	}
}



int main(string[] argv)
{




	auto asize = A.classinfo.init.length;
	auto bsize = A.B!(0).sizeof;
	A a = new A();
	auto x = a.b1.Parent();
	auto y = a.b2.Parent();
	


More information about the Digitalmars-d mailing list