Is it possible to use templates to implement something like the `@show` macro from the Julia programming langauge in D?

WraithGlade anonymous at noreply.com
Mon Sep 9 20:52:09 UTC 2024


On Monday, 9 September 2024 at 17:56:04 UTC, monkyyy wrote:
> On Monday, 9 September 2024 at 17:39:46 UTC, WraithGlade wrote:
>> 
>
> import std;
> auto parse(char[] s)=>s[9..$-2];
> void show(T,string file= __FILE__,int line=__LINE__)(T t){
>     writeln(File(file).byLine.drop(line-1).front.parse," == 
> ",t);
> }
> void main(){
>     int i=3;
>     show(i++ + ++i * i);
>     show(i);
> }

I tested this version on my machine and the output isn't correct. 
It gets cut off.

Here's the reformatted and slightly altered version I tested:

```
import std;

auto parse(char[] s) => s[9 .. $ - 2];

void show(T, string file = __FILE__, int line = __LINE__)(T t) {
   File(file)
     .byLine
     .drop(line - 1)
     .front
     .parse
     .writeln(" == ", t);
}

void main(){
   int i = 3;
   show(i++ + ++i * i);
   show(i);
}
```

It outputs this erroneous result:

```
+ + ++i * i) == 28
  == 5
```

This is not that surprising considering it uses hardcoded numbers 
and doesn't look right.

Also, moving the built EXE out of the source code directory and 
into a different folder causes the program to crash when it runs 
due to not being able to find the source code file.

That seems to indicate that this code's file reading doesn't 
actually happen in compile-time. Maybe there are compiler build 
options for D that'll write this in in compile time though?

In any case, this version seems more brittle than the others at 
least


More information about the Digitalmars-d-learn mailing list