A case for opImplicitCast: making string search work better
grauzone
none at example.net
Fri May 15 06:36:51 PDT 2009
downs wrote:
> Consider this type:
>
> struct StringPosition {
> size_t pos;
> void opImplicitCast(out size_t sz) {
> sz = pos;
> }
> void opImplicitCast(out bool b) {
> b = pos != -1;
> }
> }
>
> Wouldn't that effectively sidestep most problems people have with find returning -1?
>
> Or am I missing something?
Could work, but it looks overcomplicated. It could be intuitive, but
even then someone new would not be able to figure out what is actually
going on, without digging deep into the internals of the library (or the
D language).
I like my way better (returning two slices for search). Also, it
wouldn't require this:
> Of course, this would require a way to resolve ambiguities, i.e. functions/statements with preferences - for instance, if() would "prefer" bool over int. I don't know if this is possible.
...and with my way, it's very simple to check if the search was successful.
e.g.
void myfind(char[] text, char[] search_for, out char[] before, char[]
after);
char[] before, after;
myfind(text, something, before, after);
//was it found?
bool was_found = !!after.length;
//where was it found?
int at = before.length;
Both operations are frequently needed and don't require you to reference
text or something again, which means they can be returned by other
functions, and you don't need to break the "flow" by putting them into
temporary variables.
With multiple return values, the signature of myfind() could become
nicer, too:
auto before, after = myfind(text, something);
(Or at least allow static arrays as return values for functions.)
Am _I_ missing something?
More information about the Digitalmars-d
mailing list