www.digitalmars.com         C & C++   DMDScript  

digitalmars.D.learn - Unable to pass shared class method as delegate

reply d coder <dlang.coder gmail.com> writes:
Greetings

I am facing problem passing a shared class method as an argument to a
function. Look at the following minimized code snippet.

class Foo {
  shared // compiles when commented out
    void bar() {}
}

void frop(void delegate() dg) {
}

void main() {
  shared Foo foo = new shared(Foo);
  frop(&foo.bar);
}

I get the following errors (using dmd 2.052)
dg.d(11): Error: function dg.frop (void delegate() dg) is not callable using
argument types (void delegate() shared)
dg.d(11): Error: cannot implicitly convert expression (&foo.bar) of type
void delegate() shared to void delegate()

Please suggest a valid signature for the function frop, so that it can take
shared delegates.

Regards
- Puneet
Apr 24 2011
parent reply Robert Clipsham <robert octarineparrot.com> writes:
On 24/04/2011 15:40, d coder wrote:
 Greetings

 I am facing problem passing a shared class method as an argument to a
 function. Look at the following minimized code snippet.

 class Foo {
    shared // compiles when commented out
      void bar() {}
 }

 void frop(void delegate() dg) {
 }

 void main() {
    shared Foo foo = new shared(Foo);
    frop(&foo.bar);
 }

 I get the following errors (using dmd 2.052)
 dg.d(11): Error: function dg.frop (void delegate() dg) is not callable
 using argument types (void delegate() shared)
 dg.d(11): Error: cannot implicitly convert expression (&foo.bar) of type
 void delegate() shared to void delegate()

 Please suggest a valid signature for the function frop, so that it can
 take shared delegates.

 Regards
 - Puneet
I've copy and pasted my reply to Benjamin below, you should be able to adapt it to your needs: The only way I've found to do this that works is using an alias - this is probably worth a bug report if there isn't one already. ---- class A { // Note that you get forward reference errors if you opt to // infer the return type here. That's also a bug. void method(const const(char[]) str) shared { } } alias typeof(&A.method) shdg; void foo(shdg foo) { } void main() { foo(&A.method); } ---- -- Robert http://octarineparrot.com/
Apr 24 2011
parent d coder <dlang.coder gmail.com> writes:
 I've copy and pasted my reply to Benjamin below, you should be able to
 adapt it to your needs:
Stupid me. Should have checked the list before posting.
 The only way I've found to do this that works is using an alias - this is
 probably worth a bug report if there isn't one already.
I checked and found that this is already reported http://d.puremagic.com/issues/buglist.cgi?quicksearch=shared+delegate And since Walter says that const issues are high on his priority list, I hope this would get resolved soon. Regards - Puneet
Apr 24 2011