Char.length

Jane Doe via Digitalmars-d digitalmars-d at puremagic.com
Thu Jul 10 10:01:44 PDT 2014


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?



More information about the Digitalmars-d mailing list