Alternative to C++ macro in D

Meta jared771 at gmail.com
Sun Nov 3 23:25:26 UTC 2019


On Sunday, 3 November 2019 at 16:55:36 UTC, Vinod K Chandran 
wrote:
> Hi all,
> I can do this in C++. #include <iostream>
> using namespace std ;
>
> #define end };
> #define log(x)  cout << x << endl
> #define wait std::cin.get()
>
>
> int main() {
>     log("Trying to avoid the visual clutter aused by closing 
> curly braces") ;
>     string myStr = "Now, code looks more elegant" ;
>     log(myStr) ; mixin template cToD(string code)

`log` and `wait` are straightforward. Just write a function:

import std.stdio;
void log(T)(T x) { writeln(x); }
void wait() { readln(); }

However, you can't do things like `#define end }`. The D language 
intentionally disallows doing stuff like this. If you *really* 
want to do this, you can sort of emulate it with mixins:

mixin template cToD(string code)
{
     import std.array: replace;
     mixin(code.replace("end", "}"));
}

mixin cToD!`
     int main() {
         log("Trying to avoid the visual clutter aused by closing 
curly braces") ;
         string myStr = "Now, code looks more elegant" ;
         log(myStr) ;
         wait ;
         return 0;
     end
`;

But I would strongly recommend against it.


More information about the Digitalmars-d-learn mailing list