const and non-const member function

Regan Heath regan at netmail.co.nz
Thu Jul 26 04:13:24 PDT 2007


Christian Kamm wrote:
> Well, the original poster basically wanted it to be possible to have
> 
> class Container(T)
> {
>   int opApply(int delegate(ref T) dg);
>   const int opApply(int delegate(ref const(T)) dg);
> }
> 
> such that foreach would work on const(Container!(T)) and Container!(T)
> alike, using the correct types. To me, that seems pretty reasonable.

Initially I thought it would overload on the 'ref' part of the delegate 
in opApply, eg.

class Container
{
	int[] array;
	
	//called when 'ref' not used, suitable for 'const' objects
	int opApply(int delegate(int) dg)
	{
		int result = 0;
		for (int i = 0; i < array.length; i++)
		{
			result = dg(array[i]);
			if (result) break;
		}
		return result;
	}

	//called when 'ref' used, not suitable for 'const' objects
	int opApply(int delegate(ref int) dg)
	{
		int result = 0;
		for (int i = 0; i < array.length; i++)
		{
			result = dg(array[i]);
			if (result) break;
		}
		return result;
	}
}

Current D implementation expects the delegate to have 'ref' in it, 
anything else is an error and foreach on a const object gives:
   Error: a.opApply can only be called on a mutable object

Instead it could, on a const object look for:
   int opApply(int delegate(Type) dg)

and on non-const:
   int opApply(int delegate(ref Type) dg)

Regan


More information about the Digitalmars-d-learn mailing list