Is it possible to override and overload class Object?

Salih Dincer salihdb at hotmail.com
Mon Sep 18 21:21:45 UTC 2023


Hi All,

My problem is actually about the `new` operator.  As far as I 
know, we cannot overload it.  Therefore, all the operators that I 
use to create arrays with basic types work fine, but I need an 
extra struct Array to use it in my own type (struct Payload in 
the example).

Is there a simpler way to use the `+=` and `~=` operators on an 
array of my own type?

```d
struct Array(T)
{
   T* ptr;
   size_t length;
   
   ref auto opIndex(size_t i)
     => ptr[i];

   ref auto opIndex()
     => this;
   
   auto opSlice(size_t beg, size_t end)
     => Array(&ptr[beg], end - beg);

   void opOpAssign(string op)(int rhs)
   if(op == "+")
   {
     foreach(i; 0..length)
     {
       ptr[i] += rhs;
     }
   }

   void opOpAssign(string op)(string rhs)
   if(op == "~")
   {
     foreach(i; 0..length)
     {
       ptr[i] ~= rhs;
     }
   }

   auto toString(ToSink sink) const
   {
     sink("[");
     const limit = length - 1;
     foreach(i; 0..limit)
     {
       sink.fmt("%s, ", ptr[i]);
     }
     sink.fmt("%s]", ptr[limit]);
   }
}

struct Payload(T)
{
   string id;
   T value;

   alias opCall this;

   this(T x) { value = x; }

   auto opCall(T x)
     => value = x;

   auto opCall() inout
     => value;

   auto opOpAssign(string op : "+")(T x)
     => value += x;

   auto opOpAssign(string op : "~")(string x)
     => id ~= x;
   
   auto toString(ToSink sink) const
     => sink.fmt("%s: %s", id, value);
}

alias ToSink = void delegate(const(char)[]);

import std.stdio, std.format: fmt = formattedWrite;
alias Type =
     //Payload!
     int;
enum len = 4;

void main()
{
   auto arr = new Type[len];
   arr[] += Type(1);

   if(!is(Type == int))
     arr[] += cast(Type)1;
   arr.writeln;

   auto payloads = Array!Type(arr.ptr, arr.length);

   foreach(i; 0..len)
     payloads[i] = i + 1;

   payloads[] += 4;
   payloads.writeln;
   
   static if(!is(Type == int))
   {
     foreach(i, str; ["beş", "altı", "yedi", "sekiz"])
       payloads[i].id = str;
     payloads[] ~= " sayısı";
     payloads.writeln;
   }
}
```
**Playground:** https://run.dlang.io/is/qKKSok

Also please try and remove comment on line 74...

SDB at 79


More information about the Digitalmars-d mailing list