compile-time variables?

Pragma ericanderton at yahoo.removeme.com
Tue May 22 12:40:56 PDT 2007


Fraser wrote:
> In particular, I want a mixin template that mixes in a  unique numeric ID as part of a function every time it's used in a mixin. 

This is possible, but it will take some mildly ugly code to accomplish*.  The major hurdle to overcome is that templates 
are effectively stateless.  This is because every template invocation is dependent upon its arguments and global 
constants for evaluation, and is unable to change anything but its own definition.  The result is that there's no 
compile-time analog for simple stuff like this:

uint value;
void Counter(){
   value++;
}

... since 'Counter' modifies 'value', which would be a stateful evaluation.

The solution is to have the template evaluate to a counter value that is used as an argument for subsequent calls to the 
template.

// un-tested
template Counter(){
	const uint Counter = 1;
}

template Counter(lastCounter){
	const uint Counter= lastCounter + 1;
}

tempalte MyTemplate(){
	alias Counter!() first;
	alias Counter!(first) second;
	alias Counter!(second) last;
	alias last next; // use MyTemplate!().next where needed to keep counting
}

The gist is to keep passing around your 'counter' as you would an object at runtime.  It's kind of ugly this way, but it 
should clean up a little if you use CTFE:

// un-tested
uint Counter(){
	return 1;
}

uint Counter(in uint value){
	return value+1;
}

uint MyFn(){
	const auto first = Counter();
	const auto second = Counter(first);
	const auto third = Counter(second);
	return third;
}

(* welcome to meta-programming)

-- 
- EricAnderton at yahoo



More information about the Digitalmars-d mailing list