auto & class members

Jonathan M Davis newsgroup.d at jmdavisprog.com
Mon May 21 19:22:07 UTC 2018


On Monday, May 21, 2018 14:55:36 Steven Schveighoffer via Digitalmars-d-
learn wrote:
> On 5/20/18 1:46 PM, Robert M. Münch wrote:
> > On 2018-05-20 17:40:39 +0000, Robert M. Münch said:
> >> Hi Jonathan, great! This got me a step further. So I can declare my
> >> member now. But I get an implict cast error when I try:
> >>
> >> class a {
> >>     ... myStream;
> >> }
> >>
> >> class b {
> >>     typeof(a.myStream.filter!(x => x == myMessage)) mySubStream;
> >> }
> >>
> >> void myFunc() {
> >>     a myA = new a();
> >>     b myB = new b();
> >>
> >>     myB.mySubstream = myA.myStream.filter!(x => x == myMessage);
> >> }
> >>
> >> This gives (unnecessary stuff stripped):
> >>
> >> Error: cannot implicitly convert expression filter(...) of type
> >> app.myFunc.filter!(x => x == myMessage) to app.b.filter!(x => x ==
> >> myMessage)
> >
> > Answering myself: Using an alias helps.
> >
> > alias typeof(a.myStream.filter!(x => x == myMessage)) myMessageType;
>
> So the issue here is that the lambda function inside myFunc is DIFFERENT
> than the one inside b. They are both the same function, but with
> essentially different names.
>
> When you use the alias, both are using the same exact lambda.
>
> I see you are casting now as well, which looks horrible to me -- if you
> change something in your lambda now you are in for some trouble.
>
> What may make more sense (both for type sanity and for code reuse) is to
> wrap your call to filter into one place so it can be used wherever you
> need it:
>
> auto wrapStream(S)(S str) { return str.filter!(x => x == myMessage); }
>
> class b
> {
>     typeof(wrapStream(a.init.myStream)()) mySubStream;
> }
>
> void myFunc() {
>     a myA = new a;
>     b myB = new b;
>     myB.mySubstream = myA.myStream.wrapStream;
> }

That's basically what I was suggesting that he do, but I guess that I wasn't
clear enough.

- Jonathan M Davis




More information about the Digitalmars-d-learn mailing list