Delegates and classes for custom code.

Chris Katko ckatko at gmail.com
Wed Apr 18 01:12:33 UTC 2018


That was all pseudo-code typed by hand.

I got my code to work today. I don't know if it's the prettiest 
it can be, but it works:

// TESTING ACCESS TO the OWNING function
//-------------------------------------------
class test_window
	{
	float x;
	float y;
	
	void draw_text(string text)
		{
		writeln(text);		
		}

	this( void function(test_window) onDraw  )
		{	
		this.onDraw = onDraw;
		}

	void run() //called every frame
		{
		onDraw(this);
		}

	void function (test_window) onDraw;
	}


void test_dialog()
	{
	auto t = new test_window(function void(test_window ptr)
		{
		with(ptr)
			{
			draw_text( format("Hello, world. [x,y]=[%f,%f]", x, y));
			}
		});
		
	t.run();
	}





And a second attempt/version:





// TESTING ACCESS to anything
// ----------------------------------------------------------

struct data_to_access_t
	{
	int tacos;
	}

struct data_to_access2_t
	{
	struct beans
		{
		int x;
		};
		
	beans b;
	}

class abc(T)
	{
	int x;
	void delegate(T) run_delegate;
		
	T data;
		
	this(T t, void delegate(T) d)
		{
		data = t;
		run_delegate = d;
		}
	
	void execute()
		{
		run_delegate(data);
		}
	}

void test_dialog_anything()
	{	
	data_to_access_t  d;
	data_to_access2_t d2;
	d.tacos = 4;
	d2.b.x  = 5;

	auto x = new abc!data_to_access_t ( d, (d) => writefln("test  
%d", d.tacos)  );
	auto y = new abc!data_to_access_t ( d, (d){writefln("test  %d", 
d.tacos);}  );
	auto z = new abc!data_to_access2_t(d2, delegate void 
(d2){writefln("test2 %d", d2.b.x);}  );
	
	x.execute();
	y.execute();
	z.execute();
	}





My only questions are:

  -  is there any way to make it "smart" enough to take the type 
of the argument, instead of me manually giving it a type.

	auto x = new abc!data_to_access_t ( d, (d) => writefln("test  
%d", d.tacos)  );
becomes
	auto x = new abc( d, (d) => writefln("test  %d", d.tacos)  );

  - Is there any way to eliminate the first d? Which is 
essentially a "this" pointer.

	auto x = new abc!data_to_access_t ( d, (d) => writefln("test  
%d", d.tacos)  );
becomes
	auto x = new abc!data_to_access_t ( (d) => writefln("test  %d", 
d.tacos)  );

  - And preferably, if possible, both. But I'll take what I can 
get.


More information about the Digitalmars-d-learn mailing list