Operator macros in D

I am transferring some code written in C ++ to D. At some point I introduced a convenient macro containing the task. how

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

So, I use macros to

  • access to the actual character and its string and

  • perform the task.

How to achieve this in D?

+6
source share
1 answer

You can use the mixin operator to convert a string to code at compile time, for example:

 mixin("value = 123;"); 

The following function generates a string containing the statement, which will be the closest equivalent to your C macro:

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

What would you use then:

 mixin(soConvenient!x); // equivalent to 'so_convenient(x) in C 
+5
source

All Articles