www.digitalmars.com         C & C++   DMDScript  

digitalmars.D.learn - mixing array and string .find()

reply Brian <digitalmars brianguertin.com> writes:
is it possible to write a generic .find function for arrays that ignores 
strings and so doesn't cause conflicts? I think in D2 its easy by putting 
an if() constraint on the template, but is it possible in D1? like:

int find(T)(T[] array, T obj) {
	foreach (i, v; array) {
		if (v == obj)
			return i;
	}
	return -1;
}

this conflicts with std.string.find, so i have to import one of them 
statically and use it like.
std.string.find("mystr", "s");

i want to be able to just have:
int[] arr;
arr.find(5);

string s;
s.find("foo");
Mar 23 2009
next sibling parent reply "Denis Koroskin" <2korden gmail.com> writes:
Try the following:

int find(T)(T[] array, T obj) if (!is(T : char))
{
	foreach (i, v; array) {
		if (v == obj)
			return i;
	}
	return -1;
}
Mar 23 2009
parent Jarrett Billingsley <jarrett.billingsley gmail.com> writes:
On Mon, Mar 23, 2009 at 9:11 PM, Denis Koroskin <2korden gmail.com> wrote:
 Try the following:

 int find(T)(T[] array, T obj) if (!is(T : char))
 {
 =A0 =A0 =A0 =A0foreach (i, v; array) {
 =A0 =A0 =A0 =A0 =A0 =A0 =A0 =A0if (v =3D=3D obj)
 =A0 =A0 =A0 =A0 =A0 =A0 =A0 =A0 =A0 =A0 =A0 =A0return i;
 =A0 =A0 =A0 =A0}
 =A0 =A0 =A0 =A0return -1;
 }
in D1.
Mar 23 2009
prev sibling next sibling parent Jarrett Billingsley <jarrett.billingsley gmail.com> writes:
On Mon, Mar 23, 2009 at 8:11 PM, Brian <digitalmars brianguertin.com> wrote:
 is it possible to write a generic .find function for arrays that ignores
 strings and so doesn't cause conflicts? I think in D2 its easy by putting
 an if() constraint on the template, but is it possible in D1? like:
D2's overload sets would help here more than an if() constraint. But even still, it might be ambiguous. You don't actually have to import one statically. Just alias the one you want to take precedence in the current module: import std.string; import my.templates; alias my.templates.find find; Now whenever you use 'find' it will use my.templates.find.
Mar 23 2009
prev sibling parent BCS <none anon.com> writes:
Hello Brian,

 is it possible to write a generic .find function for arrays that
 ignores strings and so doesn't cause conflicts? I think in D2 its easy
 by putting an if() constraint on the template, but is it possible in
 D1? like:
 
one solution is to dump the std.string.find (or alias it) and have the templated function cover that case as well. template find(T) // untested so that might not work { int find(T[] array, T obj) { ... } static if(is(T == char) alias std.string.find find; else int find(T[] array, T[] obj) { ... } }
Mar 23 2009