Templates in classes => what is wrong?

Ali Çehreli acehreli at yahoo.com
Tue Apr 17 08:59:25 PDT 2012


On 04/17/2012 08:42 AM, Xan wrote:

 > How to get the "code" of a function or delegate
 >
 > |___string toString() {
 > |___|___return format("%s (versió %s): Domini -> Recorregut, %s(x) =
 > %s", nom, versio, nom, &funcio);
 >
 > |___}
 >
 > does not produce the desired result and &funcio without ampersand
 > produces me an error.
 >
 > So, my doubts are:
 > given a function:
 >
 > - how can I get the domain
 > - how can I get the range

I did not understand those. :(

 > - how can I get the code of the function?
 >
 > See https://gist.github.com/2394274
 >

I don't think D has any help there. You can keep the function as a 
string yourself and convert to actual code at compile time with a string 
mixin. For that to happen, the function text may be an additional 
template parameter:

import std.conv, std.stdio, std.stream, std.string;
import std.socket, std.socketstream;
import std.datetime;

class Algorisme(U,V,string funcioText) {
	string nom;
	uint versio;
	alias V delegate (U) Funcio;
	Funcio funcio;


	this(string nom, uint versio) {
		this.nom = nom;
		this.versio = versio;
		this.funcio = mixin(funcioText);
	}

	string toString() {
             return format("%s (versió %s): Domini -> Recorregut, %s(x) 
= %s",
                           nom, versio, nom, funcioText);
	}
}


alias Algorisme!(int, int, "(int a) { return 2 * a; }") AlgorismeEnters;

void main(string [] args)
{

	auto alg = new AlgorismeEnters("Doblar", 1);
	writeln(alg);

}

Ali



More information about the Digitalmars-d-learn mailing list