hijacking a class's members

Stanislav Blinov blinov at loniir.ru
Wed Aug 4 03:44:49 PDT 2010


  04.08.2010 14:11, Rory Mcguire wrote:
> Hi,
>
> The code below is my beginning to attempt a class which implements any class
> and throws an exception if one tries to access any member of that class.
>
> Problem is that if I use:
> auto a1 = noinit!(A)();
>
> it works and accesses the int x() {...} member of the generated class, but
> if I use:
> A a1 = noinit!(A)();
>
> it accesses A.x instead of the generated classes x.
>
> So am I wrong in making a sub class have a member function which hides a
> parent class's member variable or is the compiler wrong and it should
> generate a call to generated sub class?
>
>
> Thanks!!!
> -Rory
>
>
>
>
>
>
>
>
>
>
>
> ================================================
> import std.algorithm;
> import std.contracts;
> import std.traits;
>
> class A {
> 	int x;
> }
>
> string thrower(T)(string name) {
> 	static if (isNumeric!T) {
> 		return "@property ref "~ T.stringof ~" "~ name ~"() {
> throw new Exception(\"Uninitialized access!\"); }"
> 				"@property ref "~ T.stringof ~"
> "~ name ~"(int ignored) { throw new Exception(\"Uninitialized access\"); }";
> 	} else {
> 		return "error";
> 	}
> }
> string build(alias T, alias generator)(string myname) {
> 	string s = "auto "~ myname ~" = new class "~T.stringof~" {
> invariant() { throw new Exception(\"inv\");}\n";
> 	foreach (i,t; typeof(T.tupleof)) {
> 		string name = find(T.tupleof[i].stringof, '.');
> 		enforce(name.length>= 2);
> 		name = name[1..$];
> 		//pragma(msg, t," ", A.tupleof[i]);
> 		s ~= "\t"~generator!t(name) ~"\n";
> 	}
> 	return s~ "};";
> }
>
> auto noinit(alias T)() {
> 	mixin(build!(T,thrower)("tmp"));
> 	return tmp;
> }
>
>
> void main() {
> 	A a = noinit!(A)();
> 	auto a1 = noinit!(A)();
> //	pragma(msg, build!(A,thrower)("Athrower"));
> 	
> 	int i = a.x = 3; // uses A.x not the generated ??.x
> 	int j = a1.x = 3; // uses ??.x
> 	assert(a.x == 3);
> }
>
> =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
> Filtered-With-Copfilter: Version 0.84beta4 (ProxSMTP 1.8)
> Copfilter-Filtered-With: SpamAssassin 3.2.5
> Copfilter-Virus-Scanned: ClamAV 0.94.2
> by Markus Madlener @ http://www.copfilter.org
>
Hi,

You're working with 'a' through 'class A' public interface, because you 
plainly declared 'a' to be of 'class A'. A.x is not a function, but a 
member variable, so the compiler fairly accesses it as it should.

Regards,
Stanislav Blinov



More information about the Digitalmars-d-learn mailing list