Unmanaged drop in replacemet for [] and length -= 1

Joerg Joergonson via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Sat Jun 18 14:55:31 PDT 2016


I wanted to switch to std.container.Array but it doesn't seem to 
mimic [] for some odd ball reason. I threw this class together 
and it seems to work.

The only problem is that I can't do

carray.length -= 1;

I can't override `-=` because that is on the class. can I 
override it for length somehow or do I have to create a length 
wrapper class that has it overridden in it? Or is there a way to 
do it in cArray?

Basically I want to support code that does something like

auto x = [];
x.length -= 1;

and not have to rewrite that to x.length = x.length - 1;




public class cArray(T)
{
	Array!T data;
		
	public void assumeSafeAppend() { };

	public @property int length()
	{
		return data.length;
	}

	public @property int length(int len)
	{
		for(int i = 0; i < len; i++)
			data.removeBack();
		return data.length;
	}

	ref T opIndex(int i) { return data[i]; }
     @property int opDollar(size_t dim : 0)() { return 
data.length; }

	this() { data = Array!T(); }


	int opApply(int delegate(ref T) dg)
     {
         int result = 0;

         for (int i = 0; i < data.length; i++)
         {
             result = dg(data[i]);
             if (result)
                 break;
         }
         return result;
     }

	int opApplyReverse(int delegate(ref T) dg)
     {
         int result = 0;

         for (int i = 0; i < data.length; i++)
         {
             result = dg(data[i]);
             if (result)
                 break;
         }
         return result;
     }


	void opOpAssign(string op)(T d)
	{
		if (op == "~")
		{
			data ~= d;
		}
	}

	bool canFind(T)(T d)
	{
		for(int i = 0; i < data.length; i++)
		{
			if (data[i] == d)
				return true;
		}
		return false;
	}
}


More information about the Digitalmars-d-learn mailing list