Is there an equivavlent to C# boxing in D?

Ali Çehreli acehreli at yahoo.com
Sat Feb 12 22:38:42 UTC 2022


On 2/11/22 16:41, H. S. Teoh wrote:

 > How about this?
 >
 > --------
 > 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
 > --------

I can't resist adding the convenience function. :)

auto boxed(T)(T val) {
   return new Boxed!T(val);
}

void main() {
   // Sweet:
   auto a = boxed(123);

   // Sweet too:
   auto b = 456.boxed;
}

Ali



More information about the Digitalmars-d-learn mailing list