Unable to pass shared class method as delegate

Robert Clipsham robert at octarineparrot.com
Sun Apr 24 07:45:13 PDT 2011


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/


More information about the Digitalmars-d-learn mailing list