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
access the actual symbol and its string and
make an assignment.
How do I achieve this in D?
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With