Thread overview
Bind object to member function
Aug 13, 2006
Li Jie
Aug 13, 2006
Derek Parnell
Aug 13, 2006
Kirk McDonald
Aug 14, 2006
BCS
August 13, 2006
class Test{
  void a(int n){}
}

auto a = &Test.a;
auto t = new Test;
a(t, 1); // or: a.bind(t); a(1);

Is this supported?
August 13, 2006
On Sun, 13 Aug 2006 20:32:25 +0000 (UTC), Li Jie wrote:

> class Test{
>   void a(int n){}
> }
> 
> auto a = &Test.a;
> auto t = new Test;
> a(t, 1); // or: a.bind(t); a(1);
> 
> Is this supported?

I do not know what 'bind' means in this context. Is it a Java term? Why is it needed?

-- 
Derek Parnell
Melbourne, Australia
"Down with mediocrity!"
August 13, 2006
Li Jie wrote:
> class Test{
>   void a(int n){}
> }
> 
> auto a = &Test.a;
> auto t = new Test;
> a(t, 1); // or: a.bind(t); a(1);
> 
> Is this supported?

You want pointers to member functions, as C++ has. D does not have these. Rather, it has delegates, which are often more useful:

class Test {
    void a (int n) {}
}

Test t = new Test;
void delegate(int) dg = &t.a;
dg(1);

This use of delegates is documented here:
http://www.digitalmars.com/d/function.html#closures

If you're looking for pointers to member functions to implement some sort of dispatch mechanism, delegates do not directly allow this. However, there do exist hacks to allow it.

-- 
Kirk McDonald
Pyd: Wrapping Python with D
http://dsource.org/projects/pyd/wiki
August 14, 2006
Li Jie wrote:
> class Test{
>   void a(int n){}
> }
> 
> auto a = &Test.a;
> auto t = new Test;
> a(t, 1); // or: a.bind(t); a(1);
> 
> Is this supported?


something like this works

#	// inline function
#auto b = function(Test t)
#	{
#		t.a;
#	}
#
#auto t = new Test;
#
#	// call function
#b(t);

Add parameters to the function if a has parameters.

Also say Test has a "real c(char[],int,int)" and you don't want to set all of it's parameters, you can do this:

#int i,j;
#
#auto d = (Test test, char[] ch)
#	{
#		// take ch as arg
#		// pull i,j from context
#		return test.c(ch,i,j);
#	}
#
#	// only need one peram here
#auto ret = d(t,"foo");