Is there an equivavlent to C# boxing in D?

H. S. Teoh hsteoh at quickfur.ath.cx
Sat Feb 12 16:50:16 UTC 2022


On Sat, Feb 12, 2022 at 09:37:56AM +0000, IGotD- via Digitalmars-d-learn wrote:
> On Saturday, 12 February 2022 at 00:41:22 UTC, H. S. Teoh wrote:
[...]
> > --------
> > final class Boxed(T) {
> > 	T payload;
> > 	alias payload this; // caveat: probably not a good idea in general
> > 	this(T val) { payload = val; }
> > }
> > 
> > Boxed!int i = new Boxed!int(123);
> > int j = i; // hooray, implicit unboxing!
> > i = 321; // even this works
> > --------
[...]
> Pretty neat solution, you need an extra type but that's not much. If
> alias this would be removed in D, would tricks like these suddenly
> become impossible?
[...]

Without alias this it would be harder to pull off, yes.  So this
particular use case would constitute an example of classes + alias this
not being an anti-pattern. (Unless one were to concede that boxed types
in general are an anti-pattern... which I'm somewhat inclined to agree
with, but I won't press that point. :-P)


T

-- 
Having a smoking section in a restaurant is like having a peeing section in a swimming pool. -- Edward Burr 


More information about the Digitalmars-d-learn mailing list