Thread overview
How can I get the variable name passed as parameter from within a function?
Feb 26, 2021
Jack
Feb 26, 2021
Adam D. Ruppe
Feb 26, 2021
Jack
February 26, 2021
int a = 10;
f(a); // print "a"
int b = 10;
f(b); // print "b"

I managed to do this with alias parameter in a template:

template f(alias s, string file = __FILE__, size_t line = __LINE__)
{
    import std.exception : enforce;
    import std.string : format;

    void g()
    {
      writeln(__traits(identifier, s));
    }
}

so I can call like this:

f!(a).g; // print "a"

Are there other way to do this? Also, can I short this template function somehow to syntax f!(a) omitting the g? I couldn't find a way to set the template's body like it's a function
February 26, 2021
On Friday, 26 February 2021 at 19:32:52 UTC, Jack wrote:
> I managed to do this with alias parameter in a template:

this is the only way, it needs to be an alias template

> Also, can I short this template function somehow to syntax f!(a) omitting the g?

rename g to f. If the function inside the template's name matches the template's own name, the compiler combines them.

of course at that point you can also just write it

void f(alias var)() {
    // do your magic
}
February 26, 2021
On Friday, 26 February 2021 at 19:37:34 UTC, Adam D. Ruppe wrote:
> On Friday, 26 February 2021 at 19:32:52 UTC, Jack wrote:
>> I managed to do this with alias parameter in a template:
>
> this is the only way, it needs to be an alias template
>
>> Also, can I short this template function somehow to syntax f!(a) omitting the g?
>
> rename g to f. If the function inside the template's name matches the template's own name, the compiler combines them.
>
> of course at that point you can also just write it
>
> void f(alias var)() {
>     // do your magic
> }

thanks! i was confused about where put alias in the function parameters but of course it's in the first () meant to be used as template parameters