opApply and attributes

Paul Backus snarwin at gmail.com
Tue Jul 7 13:33:41 UTC 2020


On Tuesday, 7 July 2020 at 00:20:40 UTC, solidstate1991 wrote:
> See implementation of data structure here: 
> https://github.com/ZILtoid1991/collections-d/blob/master/source/collections/treemap.d#L565
>
> If I try to compile this code, it'll fail, limiting it's 
> usecase:
>
> @safe pure unittest {
> 	alias IntMap = TreeMap!(int, int, false);
> 	IntMap test;
> 	test[5] = 5;
> 	test[7] = 7;
> 	test[3] = 3;
> 	foreach(elem, key; test) {
> 		assert(elem == key);
> 	}
> }

You can make opApply a template:

     int opApply(Dg)(Dg dg)
         if (is(Dg : scope int delegate(ref E)))
     {
         // etc.
     }

Because `scope int delegate(ref E) @safe` implicitly converts to 
`scope int delegate(ref E)`, this version will accept both @safe 
and non- at safe delegates. (And likewise for the other function 
attributes.)


More information about the Digitalmars-d-learn mailing list