digitalmars.D.learn - How can I get the variable name passed as parameter from within a
- Jack (20/20) Feb 26 2021 int a = 10;
- Adam D. Ruppe (8/11) Feb 26 2021 rename g to f. If the function inside the template's name matches
- Jack (4/15) Feb 26 2021 thanks! i was confused about where put alias in the function
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
Feb 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 templateAlso, 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 }
Feb 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: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 parametersI managed to do this with alias parameter in a template:this is the only way, it needs to be an alias templateAlso, 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 }
Feb 26 2021