www.digitalmars.com         C & C++   DMDScript  

digitalmars.D - simplify code with macro

Hello, I've got a simple question about what could be done with macros.

void req(lazy bool cond) { if (! cond()) throw new Exception(""); };

void main() {
	try {
	req(true);
	Stdout("everything fine");
	req(false);
	/*this is not reached*/
	} catch {};
}


Could macros be used to turn this into:
---------------------------------------
macro:
req( ... ) -- should be expanded to --> if (! ... ) return false;

void main() {
	req(true);
	Stdout("everything fine");
	req(false);
	Stdout("should not be reached");
}


So the expanded version would be:
---------------------------------
void main() {
	if (! true) return false;
	Stdout("everything fine");
	if (! false) return false;
	Stdout("should not be reached");
}


This could already be done with mixin:
------------------------------------------
template req(char[] cond) {
	const req = "if (! " ~ cond ~ ") return false;";
}

void main() {
	mixin(req!("true"));
	Stdout("everything fine");
	mixin(req!("false"));
	Stdout("should not be reached");
}

But the mixin approach is not what I intend to: Simplify the syntax.

 From the syntax point of view, usage of exceptions is currently the 
best. But it would be a lot of overhead in my case, where a lot of
these "req ( cond )" are used. So a lot of exceptions would have to be 
thrown.


Thanks for your replys in advance !

Daniel
May 18 2007