On Friday, 11 October 2024 at 03:01:54 UTC, Alexa Schor wrote:
Hello!
I've been working on building some debug print functions and
have been using the `__traits(identifier, x)` to get the name
of parameters passed into a function, trying as best I can to
replicate the functionality of the useful C++ [`#`
operator](https://gcc.gnu.org/onlinedocs/cpp/Stringizing.html)
to turn a macro argument into a string literal.
This works fine for a single aliased argument
```d
void printName(alias val)() {
writeln(__traits(identifier, val));
}
```
but I wanted to see if I could get it working in a variadic
function. However, attempting with a static foreach, it seems
that the `__traits(identifier)` value is not preserved:
```d
void printNames(T...)(T args) {
static foreach(val; args)
writeln(__traits(identifier, val));
}
```
Instead,
```d
void main() {
float x = 123;
float y = 456;
printName!(x);
printName!(y);
printNames(x, y);
}
```
yields
```d
x
y
__param_0
__param_1
```
*(I guess this makes sense, as it's no longer a aliased
template argument and now is a function argument, although I
thought I remember reading that variadic function arguments
were aliased?)*
I suppose my question is: is there any way to determine the
original name of a value passed into a variadic function, in
the way that the `printName` function above does?
I'm quite new to this language, so I very much apologize if
this question is ill-formed or based on incorrect assumptions.
I also realize this is a weird application, so I wouldn't be
too surprised if this just isn't possible, but I figured I'd
ask here.
Thank you,
Alexa
```d
import std.stdio, core.interpolation;
void show(Args...)(InterpolationHeader hdr, Args args,
InterpolationFooter ftr)
{
foreach (arg; args)
{
static if (is(typeof(arg) == InterpolatedExpression!code,
string code))
code.write;
else static if (is(typeof(arg) == InterpolatedLiteral!str,
string str))
str.write;
else write(" = ", arg);
}
writeln();
}
void main()
{
int a = 5, b = 22;
show(i`$(a), $(b), $(a + b)`);
// a = 5, b = 22, a + b = 27
}
```
SDB@79