const debacle

Daniel919 Daniel919 at web.de
Mon Mar 24 04:59:12 PDT 2008


> How do you declare a function that takes an array, is not allowed to change 
> the array, but returns a slice into the argument array, and the return type 
> matches the argument type.

What about:

T slice(T)(const T s, int start, int end)
{
	return cast(T) s[start .. end];
}

void main()
{
	char[] s1 = "0123456789".dup;
	const(char)[] s2 = "0123456789";
	const(char[]) s2b = "0123456789";
	invariant(char)[] s3 = "0123456789";
	invariant(char[]) s3b = "0123456789";
	assert (is(typeof(slice(s1,1,4)) == typeof(s1)));
	assert (is(typeof(slice(s2,1,4)) == typeof(s2)));
	assert (is(typeof(slice(s2b,1,4)) == typeof(s2b)));
	assert (is(typeof(slice(s3,1,4)) == typeof(s3)));
	assert (is(typeof(slice(s3b,1,4)) == typeof(s3b)));
}



More information about the Digitalmars-d mailing list