www.digitalmars.com         C & C++   DMDScript  

digitalmars.D.learn - Delegates and nested classes...

reply Markus Dangl <danglm in.tum.de> writes:
Content-Type: text/plain; charset=ISO-8859-15; format=flowed
Content-Transfer-Encoding: 7bit

I expected the following code to print "Hello", but it doesn't. Since a 
nested class has access to its enclosing classes' members, i assumed it 
could also return delegates to its methods. Where am i wrong - or is it 
a bug?

# module nestedclass;
#
# private import std.stdio;
#
# class Foo
# {
#     class Bar
#     {
#         void delegate() getDelegate()
#         {
#             return &sayHello;
#         }
#     }
#     Bar bar;
#
#     void sayHello()
#     {
#         writefln("Hello");
#     }
#
#     this()
#     {
#         bar = new Bar();
#     }
# }
#
# int main(char[][] argv)
# {
#     Foo foo = new Foo();
#     void delegate() sayHello = foo.bar.getDelegate();
#     sayHello();
#
#     return 0;
# }
May 21 2006
parent Tom S <h3r3tic remove.mat.uni.torun.pl> writes:
Markus Dangl wrote:
 I expected the following code to print "Hello", but it doesn't. Since a 
 nested class has access to its enclosing classes' members, i assumed it 
 could also return delegates to its methods. Where am i wrong - or is it 
 a bug?

Looks like a bug to me... you could try the following workaround: class Foo { Foo outer() { return this; } ... class Bar { void delegate() getDelegate() { return &outer.sayHello; } } ... } -- -----BEGIN GEEK CODE BLOCK----- Version: 3.1 GCS/M d-pu s+: a-->----- C+++$>++++ UL P+ L+ E--- W++ N++ o? K? w++ !O !M V? PS- PE- Y PGP t 5 X? R tv-- b DI- D+ G e>+++ h>++ !r !y ------END GEEK CODE BLOCK------ Tomasz Stachowiak /+ a.k.a. h3r3tic +/
May 21 2006