How can I dump an expression into log and execute it

H. S. Teoh via Digitalmars-d digitalmars-d at puremagic.com
Fri Jul 11 07:14:21 PDT 2014


On Fri, Jul 11, 2014 at 08:57:26AM +0200, Jacob Carlborg via Digitalmars-d wrote:
> On 11/07/14 03:35, Delorien wrote:
> >Hi,
> >
> >I have a C macro, which takes an argument, log it and call a
> >function.  So, if I had a source code like this:
> >
> >{
> >   _logfx(x + 10);
> >}
> >
> >the actual code would be
> >
> >   DebugLog("x + 10");
> >   fx(x + 10);
> >
> >Can I make similar tricks in the D language?
> 
> No, I don't think so. Not without passing it as a string to begin
> with. Or AST macros, which we don't have.
[...]

Sure you can:

	auto logAndCall(alias func, string expr)() {
		DebugLog(expr);
		return func(mixin(expr));
	}

	double myFunc(double arg) { ... }
	auto result = logAndCall!(myFunc, q{1.0 + 2.0/4});


T

-- 
I've been around long enough to have seen an endless parade of magic new techniques du jour, most of which purport to remove the necessity of thought about your programming problem.  In the end they wind up contributing one or two pieces to the collective wisdom, and fade away in the rearview mirror. -- Walter Bright


More information about the Digitalmars-d mailing list