www.digitalmars.com         C & C++   DMDScript  

digitalmars.D.learn - Putting function pointers / delegates into associative array.

reply Mark <tigchelaarm mymacewan.ca> writes:
What I'm trying to do here is to be able to call a function based 
off of a key.

I'm not sure how to do this, I've been messing around a bit, but 
the compiler doesn't like what I'm doing.

Im getting:
test.d(20): Error: cannot implicitly convert expression &this.A 
of type void delegate() to void function()
test.d(21): Error: cannot implicitly convert expression &this.B 
of type void delegate() to void function()


I'm new to the idea of using delegates. Here's the code:

void main() {

	tester t = new tester();

	t.callFuncs('a');
	t.callFuncs('b');

}

class tester {

	private void delegate() [char] funcs;

	this() {
		void delegate() a;
		void delegate() b;
		a.funcptr = &A;
		b.funcptr = &B;
		this.funcs = ['a': a, 'b': b ];
	}

	public void callFuncs(char a) {
		auto t = funcs[a];
		t();
	}

	private void A() {
		writeln("A");
	}

	private void B() {
		writeln("B");
	}
}

I'm not sure how to go about this. It would be really cool if I 
can use function pointer this way.. Could someone give me a bit 
of advice as to what to do here?

I don't want to have to bust out a big case statement for this 
type of thing.

Thanks.
Jan 03 2018
parent visitor <visitor gmail.com> writes:
On Thursday, 4 January 2018 at 01:40:21 UTC, Mark wrote:
 What I'm trying to do here is to be able to call a function 
 based off of a key.
class tester { private void delegate() [char] funcs; this() { funcs = ['a': &A, 'b': &B]; } public void callFuncs(char a) { funcs[a](); } private void A() { writeln("A"); } private void B() { writeln("B"); } }
Jan 03 2018