Range to array

Jonathan M Davis jmdavisProg at gmx.com
Sat Jun 30 02:35:55 PDT 2012


On Saturday, June 30, 2012 11:06:06 Namespace wrote:
> But a Range don't match any function that accept arrays. Or
> should i prefer to use Ranges instead of arrays?

In general, functions should take ranges, not arrays. They're far more flexible 
that way. Requiring an array is generally overly restrictive. There are, of 
course, cases where you really do need to operate on an array or string, or 
where it's pointless to take anything else (e.g. if you're going to pass a 
zero-terminated string to a C function, then there's no point in taking a 
range of dchar instead of a string), but in general, functions should operate 
on ranges, not arrays. Just look at Phobos. For the most part, it operates on 
ranges, not arrays.

The only real exception in general is that if a function needs to operate on 
characters (rather than being generic with its type), then it's likely to be 
templatized on string type rather than on range type, but due to the fact that 
strings are variably length encoded, operating on them as ranges tends to be 
inefficent (which is why range-based functions frequently have overloads 
specifically for strings). So, ranges which wrap strings tend to be converted 
to strings far more often than other arrays do. But it's arguably the case 
that more of Phobos' functions which operate on strings should take ranges of 
dchar instead.

- Jonathan M Davis


More information about the Digitalmars-d-learn mailing list