Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Statement macros in D

I am porting some code I have written in C++ to D. At one point I introduced a convenience macro, that contains an assignment. Like

#define so_convenient(x) value = some_func(x,#x)

So I am using macros to

  1. access the actual symbol and its string and

  2. make an assignment.

How do I achieve this in D?

like image 842
steffen Avatar asked Apr 09 '14 20:04

steffen


1 Answers

You can use a mixin statement to convert a string into code at compile time e.g.:

mixin("value = 123;");

The following function will generate a string containing a statement which would be the closest equivalent of your C macro:

string soConvenient(alias A)()
{
    return std.string.format(
        'value = someFunc(%1$s, "%1$s");',
        __traits(identifier, A));
}

Which you would then use like this:

mixin(soConvenient!x);       // equivalent to 'so_convenient(x) in C
like image 124
beerboy Avatar answered Sep 21 '22 18:09

beerboy