identof || toIdent - feature suggestion / question

Tom S h3r3tic at remove.mat.uni.torun.pl
Sat Jul 1 01:51:24 PDT 2006


Would it be hard to add a construct to D that would convert a 
compile-time string to an identifier ?

E.g.

int identof("foo");
// would be equivalent to:
int foo;
// and
identof("int") foo;
// and
identof("int") identof("foo");


It would allow programmatic data structure construction through 
templates. It would also be useful while converting C macros like:

#define myMacro(foo) _whatever##foo
...
int myMacro(A);
_whateverA = 1;

which could then become

template myMacro(T, char[] n) {
	T identof("_whatever" ~ n);
}
...
mixin myMacro!(int, "A");
_whateverA = 1;


It wouldn't have to work exactly this way, but such functionality would 
boost D's template powers :) One could create templates that parse 
strings and create complex data structures based on them. For instance, 
I currently have code that look like this:

mixin Input!(`in`)
	.field!(int, `num`)
	.field!(int, `num2`)
.end input;

It's instantiated in a class with which it automatically registers 
itself, provides type info and iteration over its fields, registers some 
functions that are called from the class ctor, etc.
It also creates a struct that resembles

struct Data {
	int num;
	int num2;
	// one more field here
}

with one single difference... its fields must be accessed thru templates:

input.Data d;
d.f!(`num`) = 5;
// etc

instead of simply

input.Data d;
d.num = 5;
// etc


The 'identof' could fix the gap and make it pretty seamless. Then it 
could be taken one step further:

mixin Input!(`
	in {
		int num;
		int num2;
	}
`) input;


Comments ? Suggestions ?


-- 
Tomasz Stachowiak  /+ a.k.a. h3r3tic +/



More information about the Digitalmars-d mailing list