Why does stringof not like functions with arguments?
Meta via Digitalmars-d-learn
digitalmars-d-learn at puremagic.com
Thu Aug 10 07:51:22 PDT 2017
On Wednesday, 9 August 2017 at 01:39:07 UTC, Jason Brady wrote:
> Why does the following code error out with:
>
> app.d(12,10): Error: function app.FunctionWithArguments (uint
> i) is not callable using argument types ()
>
> Code:
>
> import std.stdio;
>
> void FunctionWithoutArguments() {
> }
>
> void FunctionWithArguments(uint i) {
> }
>
> void main()
> {
> writeln(FunctionWithoutArguments.stringof);
> writeln(FunctionWithArguments.stringof);
> }
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);
More information about the Digitalmars-d-learn
mailing list