Thread overview
mixing array and string .find()
Mar 24, 2009
Brian
Mar 24, 2009
Denis Koroskin
Mar 24, 2009
BCS
March 24, 2009
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");
March 24, 2009
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;
}

March 24, 2009
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.
March 24, 2009
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))
> {
>        foreach (i, v; array) {
>                if (v == obj)
>                        return i;
>        }
>        return -1;
> }
>
>

in D1.
March 24, 2009
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) { ... }
}