Thread overview
alias to struct method
Dec 22, 2017
Marc
Dec 22, 2017
Ali Çehreli
Dec 22, 2017
Mengu
December 22, 2017
How can I create a alias to a struct method?

> struct S {
>  string doSomething(int n) { return ""; }
> }

I'd like to do something like this (imaginary code):

alias doSomething = S.doSomething;

then call it by doSomething(3)

I got the following error from this code:

> Error: need 'this' for 'gen' of type 'string(int n)'

So I tried create a instance:

> alias doSomething = S().doSomething;

Changes the error to:

> app.d(96): Error: function declaration without return type. (Note that > constructors are always named this)
> app.d(96): Error: semicolon expected to close alias declaration
December 22, 2017
On 12/22/2017 09:53 AM, Marc wrote:
> How can I create a alias to a struct method?
>
>> struct S {
>>  string doSomething(int n) { return ""; }
>> }
>
> I'd like to do something like this (imaginary code):
>
> alias doSomething = S.doSomething;
>
> then call it by doSomething(3)

That can't work because there is no S object to call doSomething on. One way is to use a delegate:

struct S {
    string doSomething(int n) { return ""; }
}

void main() {
    S s;
    auto d = (int n) { s.doSomething(n); };
    d(3);
}

Ali

December 22, 2017
On Friday, 22 December 2017 at 17:53:34 UTC, Marc wrote:
> How can I create a alias to a struct method?
>
>> struct S {
>>  string doSomething(int n) { return ""; }
>> }
>
> I'd like to do something like this (imaginary code):
>
> alias doSomething = S.doSomething;
>
> then call it by doSomething(3)
>
> I got the following error from this code:
>
>> Error: need 'this' for 'gen' of type 'string(int n)'
>
> So I tried create a instance:
>
>> alias doSomething = S().doSomething;
>
> Changes the error to:
>
>> app.d(96): Error: function declaration without return type. (Note that > constructors are always named this)
>> app.d(96): Error: semicolon expected to close alias declaration

it is also possible with getMember trait but why don't you just mark that method as static?