Get name of alias parameter at compile time?

Jacob Carlborg doob at me.com
Thu Oct 15 09:17:44 PDT 2009


On 10/15/09 17:55, dsimcha wrote:
> == Quote from Lutger (lutger.blijdestijn at gmail.com)'s article
>> Denis Koroskin wrote:
>>> On Thu, 15 Oct 2009 18:22:37 +0400, dsimcha<dsimcha at yahoo.com>  wrote:
>>>
>>>> Jacob Carlborg Wrote:
>>>>
>>>>> On 10/14/09 06:36, dsimcha wrote:
>>>>>> Is there a way to get the name of an alias parameter at compile
>>>>> time?  For
>>>>>> example:
>>>>>>
>>>>>> void doStuff() {
>>>>>>       // Do stuff.
>>>>>> }
>>>>>>
>>>>>> void templ(alias fun)() {
>>>>>>      writeln(fun.stringof);  // Prints doStuff.
>>>>>> }
>>>>>
>>>>> Do you want that to print "fun" instead of "doStuff"?
>>>>
>>>> No, the whole point is that I want to print "doStuff".
>>>
>>> What's the big deal?
>>>
>>> import std.stdio;
>>>
>>> void doStuff() {
>>> }
>>>
>>> void templ(alias fun)() {
>>>       writeln(fun.stringof);   // prints "main()"
>>> }
>>>
>>> void main()
>>> {
>>>       templ!(main);
>>> }
>>>
>>> Works for both D1 and D2
>> I was a bit surprised too since the code dsimcha posted did exactly that.
>> However, change void doStuff() to void doStuff(int a) and you got an error.
>> I remembered hacking around that one, if anybody knows how to do it better
>> it would be good to know:
>> void doStuff(int a)
>> {
>> // Do stuff.
>> }
>> void templ(T...)()
>>      if (T.length==1)
>> {
>>      writeln( T.stringof[6..$-1] );
>> }
>> void main()
>> {
>>      templ!doStuff();
>> }
>
> Yeah, now that I look into it further, what you describe is exactly the problem.
> The obvious way only works for functions w/o parameters.  I simplified my example
> before I posted it and never bothered to test it.

Oh, that problem. Just use a function pointer and get the name of that 
instead, like this: 
http://www.dsource.org/projects/dstep/browser/dstep/internal/Traits.d 
(functionNameOf at line 17)



More information about the Digitalmars-d mailing list