Question

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?

Was it helpful?

Solution

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
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top