digitalmars.D - Explicitly passing `this` to methods
- Tomer Filiba (26/26) Jun 19 2014 Is there a way to explicitly pass `this` instance to a method?
- Tobias Pankrath (4/10) Jun 19 2014 Did you try: mixin("inst.f(args)");?
- Tomer Filiba (5/18) Jun 19 2014 That requires me having the names in scope, etc. I want to be
- Tobias Pankrath (12/16) Jun 19 2014 class C
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
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, -tomerDid you try: mixin("inst.f(args)");? You would need to replace f with the correct function name, i guess.
 Jun 19 2014
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, -tomerDid you try: mixin("inst.f(args)");? You would need to replace f with the correct function name, i guess.
 Jun 19 2014
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. -tomerclass 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








 
  
  
  "Tobias Pankrath" <tobias pankrath.net>
 "Tobias Pankrath" <tobias pankrath.net>