Char.length
John Colvin via Digitalmars-d
digitalmars-d at puremagic.com
Thu Jul 10 10:11:12 PDT 2014
On Thursday, 10 July 2014 at 17:01:45 UTC, Jane Doe wrote:
> One thing that bothers me quite a bit is that char's do not
> have length. This makes it difficult in templates that can take
> either strings or chars.
>
> While one can write a template that returns the length of a
> string or char, I would imagine that this could be implemented
> in the compiler more efficiently?
>
> char.length always returns 1.
>
> Similarly, it would be nice to be able to use [] on chars.
>
> char[x] returns char.
>
> Example:
>
> auto last(T)(T s) { return s[s.length-1]; }
>
> void main()
> {
> writeln(last("asdf"));
> writeln(last('c')); // fails!! But surely this should
> work!
> }
>
>
>
> http://dpaste.dzfl.pl/cba5a635d08e
>
> Error: s must be an array or pointer type, not char
> Error: no property 'length' for type 'char'
>
> Basically, I see no reason why char's can't be more confluent
> with strings, at least on the surface. I would reduce code
> bloat/specialization for no real reason.
>
> If the compile knows a type is a char then char.length = 1 and
> char[x] = char. Shouldn't be hard or cause any problems?
It looks nice on the surface but it quite quickly unravels.
string and char are very different types: one is a single-byte
value type, the other is a 16 byte (on x64) structure
representing an arbitrary length window on to arbitrary memory.
The situations where they are interchangeable in code are the
exceptions, not the rule.
More information about the Digitalmars-d
mailing list