Why does stringof not like functions with arguments?

Jason Brady via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Thu Aug 10 08:55:41 PDT 2017


On Thursday, 10 August 2017 at 14:51:22 UTC, Meta wrote:
>
> Welcome to optional parentheses hell. Please enjoy your stay.
>
> Because function calls in D can optionally omit the parens, 
> `FunctionWithArguments.stringof` is actually attempting to call 
> `FunctionWithArguments` without any arguments, and then call 
> `stringof` on the result. In other words, it's actually trying 
> to do this:
>
> writeln(FunctionWithArguments().stringof);
>
> And the D compiler is rightly telling you that you can't call 
> the function with no arguments. The easiest solution is to use 
> __traits(identifier) instead:
>
> writeln(__traits(identifier, FunctionWithArguments));
>
> You can make a handy template helper to do this for you:
>
> enum stringOf(alias symbol) = __traits(identifier, symbol);
> writeln(stringOf!FunctionWithArguments);

Wow. That makes perfect sense. I forgot stringof works only with 
expressions and that a function name is a valid expression in the 
case of UCF.

I already found the __traits as a workaround, but the template 
helper is a great idea. Thanks!


More information about the Digitalmars-d-learn mailing list