Storing templates

Simen simen.haugen at pandavre.com
Fri Mar 9 08:18:16 PST 2007


Hi.

I'm new to D, and I'm having a little problems using templates for my parser project...

I thought that I could store the functions in a map ala Function[char[]] so I can reference them as functions["TestFunc"], but I don't know how I can store the templates in any sort of list since they have different parameters/return values.
I know I can store them as void pointers, but then I need to cast them to the right type before I can use them. Then I have to have a switch statement or something to be able to cast it to the correct type based on the function name.

I also looked at std.box, and even if it would allow me to store all these functions in a list, I still need to know what object is stored to unbox it.

The important thing is that I can easily reference the functions by name and get the return value (the script is dynamically typed so no return types there). I also have to use Phobos (as my parser is written in Enki which is Phobos only).

Any pointers on how I can solve this? I'm sure this is not the best way to do this, and I'm always open for change. Perhaps I have taken the wrong approach here?


import std.stdio;

class Function(R, P...)
{
	R function(P) fp;
	public this(R function(P) fp)
	{
		this.fp = fp;
	}
}


Function!(R, P) addFunc(R, P...)(R function(P) fp)
{
	writefln("R:", typeid(R));
	writefln("P:", typeid(P));
	return new Function!(R, P)(fp);
}


int add(int a, int b)
{
	return a+b;
}


double addmore(double a, double b, double c)
{
	return a+b+c;
}


void main()
{
	auto func = addFunc(&add);
	writefln( typeid(typeof(func)) );
	writefln("add(3, 4): ", func.fp(3, 4) );
	writefln();

	auto func2 = addFunc(&addmore);
	writefln( typeid(typeof(func2)) );
	writefln("addmore(3, 4, 5): ", func2.fp(3, 4, 5) );
	writefln();
}



OUTPUT
======
R:int
P:(int,int)
dtest.Function!(int,int,int).Function
add(3, 4): 7

R:double
P:(double,double,double)
dtest.Function!(double,double,double,double).Function
addmore(3, 4, 5): 12


More information about the Digitalmars-d-learn mailing list