auto & class members

Jonathan M Davis newsgroup.d at
Sun May 20 14:49:59 UTC 2018

On Sunday, May 20, 2018 16:30:10 Robert M. Münch via Digitalmars-d-learn 
> I use the D RX lib [1] and can create a filtered stream using the auto
> keyword:
> struct a {
>   SubjectObject!myType myStream;
>   ??? mySubStream;
> }
> void myfunc(){
>   a myA = new a();
>   auto mySubStream = a.myStream.filter!(a => a == myMessage);
>   ...
> }
> The problem is, that I don't find out what the type of mySubStream is,
> which I would like to make a member of the struct, so that I can
> reference it outside the function too.
> How can I find out the type of an auto? This here seems to be a pretty
> complicated templated, nested type, whatever result.
> [1]

In cases like this, typeof is your friend. e.g. something like

typeof(myStream.filter!(a => a == myMessage)) mySubStream;

though you might have trouble with the lambda being subtly different type
even if you replace myMessage in it with something that will work in the
scope that mySubStream is being declared. However, that could be fixed by
doing something like replacing the lambda with a free function or just
creating a function that returns what you want to assign to mySubStream.
Then you could just do something like

typeof(myHelperFunc(myStream)) mySubStream;

The exact solution can get a bit annoying in cases like this (it's arguably
the biggest downside to auto returns), but typeof does provide a way out if
you can get the expression to it to work. It is easier with local variables
than member variables though, since you don't necessarily have everything
you want to use in the expression that will give the variable its value
available at the point that the variable is declared - but that's why
a helper function can help, since it provides a way to encapsulate the
expression and reuse it between the assignment and the declaration.

- Jonathan M Davis

More information about the Digitalmars-d-learn mailing list