The Phobos Put

Ali Çehreli acehreli at yahoo.com
Wed Mar 29 19:49:47 UTC 2023


On 3/29/23 12:21, ag0aep6g wrote:

 > As far as I understand, you're saying that we cannot overload on `ref`.
 > But we can. Salih's code demonstrates just that.
 >
 > void f(ref int x) {}
 > void f(int x) {}
 > void main() { int x; f(x); f(42); } /* no errors */

I thought Salih was proposing two more overloads to the existing put(). 
When I copy the existing put(), which takes 'ref R', not R[], then the 
code does not compile:

auto put(R)(R[] range, R[] source)
   => putImpl(range, source);

auto put(R)(ref R[] range, R[] source)
   => putImpl(range, source);

void putImpl(R)(ref R[] range, R[] source)
{
   assert(source.length <= range.length);
   foreach(element; source)
   {
     range[0] = element;  // range.front()
     range = range[1..$]; // range.popFront()
   }
}

void put(R, E)(ref R r, E e)
{
   // This is from Phobos <-------
}

void main() {
   enum data = [1, 0, 0, 4];
   auto arr = data;
   auto slice = arr[1..$-1];

   slice.put([2]);              // <-- ERROR
   assert(arr == [1, 2, 0, 4]);

   slice.put([3]);
   assert(arr == [1, 2, 3, 4]);

   arr[1..$-1].put([0, 0]);
   assert(arr == data);
}

Ali



More information about the Digitalmars-d-learn mailing list