www.digitalmars.com         C & C++   DMDScript  

digitalmars.D - Explicitly passing `this` to methods

reply "Tomer Filiba" <tomerfiliba gmail.com> writes:
Is there a way to explicitly pass `this` instance to a method? 
Consider the following example:

-------
class Foo {
     void f(int a) {}
}

struct Caller(alias F) {
     mixin(__traits(parent, F).stringof ~ " inst;");

     auto call(ParameterTypeTuple!F args) {
         return F(args);
     }
}

void main() {
     auto c = Caller!(Foo.f)(new Foo);
     c.call(6);
}
-------

It fails with "Error: this for f needs to be type Foo not type 
Caller!(f)", because it takes `this` from the the struct and 
tries to apply it to the method.

I tried `F(inst, args)` or `inst.F(args)` but they don't work... 
what I need is the inverse of UFCS (e.g., `func(inst,1,2,3) ==> 
inst.func(1,2,3)`)

Is there any way to overcome this?

Thanks,
-tomer
Jun 19 2014
next sibling parent "Tobias Pankrath" <tobias pankrath.net> writes:
On Thursday, 19 June 2014 at 09:16:07 UTC, Tomer Filiba wrote:

 I tried `F(inst, args)` or `inst.F(args)` but they don't 
 work... what I need is the inverse of UFCS (e.g., 
 `func(inst,1,2,3) ==> inst.func(1,2,3)`)

 Is there any way to overcome this?

 Thanks,
 -tomer

Did you try: mixin("inst.f(args)");? You would need to replace f with the correct function name, i guess.
Jun 19 2014
prev sibling next sibling parent "Tomer Filiba" <tomerfiliba gmail.com> writes:
That requires me having the names in scope, etc. I want to be 
able to use the function object, just like I could do if it 
weren't a method.


-tomer

On Thursday, 19 June 2014 at 09:22:09 UTC, Tobias Pankrath wrote:
 On Thursday, 19 June 2014 at 09:16:07 UTC, Tomer Filiba wrote:

 I tried `F(inst, args)` or `inst.F(args)` but they don't 
 work... what I need is the inverse of UFCS (e.g., 
 `func(inst,1,2,3) ==> inst.func(1,2,3)`)

 Is there any way to overcome this?

 Thanks,
 -tomer

Did you try: mixin("inst.f(args)");? You would need to replace f with the correct function name, i guess.

Jun 19 2014
prev sibling parent "Tobias Pankrath" <tobias pankrath.net> writes:
On Thursday, 19 June 2014 at 12:00:01 UTC, Tomer Filiba wrote:
 That requires me having the names in scope, etc. I want to be 
 able to use the function object, just like I could do if it 
 weren't a method.


 -tomer

class C { void methodOfC(int x) { writeln(x); }; } void main() { auto c = new C; auto method = &(c.methodOfC); method(12); } There are no method function pointer in D, but delegates work.
Jun 19 2014