Using a macro for a function signature

Anonymouse via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Tue Apr 5 06:17:38 PDT 2016


On Tuesday, 5 April 2016 at 11:35:24 UTC, pineapple wrote:
> If I have a common function signature I'm using throughout my 
> code, and I feel like there should be a way to condense it 
> using a macro. The intuitive method isn't working, but this 
> seems like something D would be able to do. What've I got wrong 
> in this example?
>
>
>
> alias somelongsignature = int(in int x);

alias somelongsignature = int function(in int);

> int examplefunc0(in int x){
>     return x * 2;
> }
>
> somelongsignature testfunc0 = examplefunc1;
> somelongsignature testfunc1 = somelongsignature {return x + 3};

somelongsignature testfunc0 = &examplefunc0;
somelongsignature testfunc1 = function(in int x){return x + 3;};
somelongsignature testfunc2 = function(x){return x + 15;};
somelongsignature testfunc3 = (in int x){return x + 20;};
somelongsignature testfunc4 = (x){return x + 25;};
somelongsignature testfunc5 = (x => x+30);
// probably more

You can't get rid of the signature completely as the functions 
still need a parameter list with x declared. You will get "Error: 
undefined identifier 'x'" otherwise. You can largely omit the 
*type* of x if it can be inferred from the signature, but you 
can't have its name be solely in the signature alias.

Parantheses are optional when calling functions without 
arguments. This is valid D:

void main() {
     import std.stdio;
     writeln;  // valid, no parantheses makes it writeln(), 
compare 'testfunc0 = examplefunc1/*()*/;'
     writeln = "Hello world!";  // valid, looks funky but helps 
with properties

     // auto doesntwork = writeln;  // invalid, writeln() returns 
void
     // auto doesntworkeither = &writeln;  // invalid, writeln is 
a template

     alias println = writeln;  // valid, aliases to templates work
     println("Hello world again!");
     println;
     println(3.14);
}

So the original code was trying to assign testfunc0 the return 
value of a call to examplefunc1(), which doesn't exist. You want 
the function pointer instead.


More information about the Digitalmars-d-learn mailing list