A case for opImplicitCast: making string search work better

Steven Schveighoffer schveiguy at yahoo.com
Fri May 15 07:10:47 PDT 2009


On Fri, 15 May 2009 09:36:51 -0400, grauzone <none at example.net> wrote:

> 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?

Your solution actually goes the opposite direction than I'd like.  That  
is, it looks more complicated than simply returning an index or a slice.   
I don't want to have to declare return values ahead of time and I'm not  
holding my breath for multiple return values.  You may be able to return a  
pair struct, but still, what could be simpler than returning an index?   
It's easy to construct the value you want (before or after), and if you  
both multiple values, that is also possible (and probably results in  
simpler code).

-Steve



More information about the Digitalmars-d mailing list