Char.length

Kiith-Sa via Digitalmars-d digitalmars-d at puremagic.com
Thu Jul 10 11:32:30 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?

Would cause unexpected behavior / hard to track errors on typos.

If you want, you can do it yourself with UFCS:

import std.traits;
size_t length(C)(C c) if(isSomeChar!C)
{
     return 1;
}
unittest
{
     assert('a'.length == 1);
}


Not sure if you can do the same for opIndex(S)(S s) 
if(isSomeString!C) , probably not.

But you can do:

auto at(T)(T t, I index) if(isIntegral!T && (isSomeChar!T || 
isSomeString!T))
{
     static if(isSomeChar!T)
     {
         assert(index == 0,
                "Non-zero index makes no sense for a single 
character);
         return t;
     }
     else
     {
         return t[index];
     }
}
unittest
{
    assert("qwe".at(1) == 'w'.at(0));
}

(Note that I didn't test any of those, it may need modification)



That said, it's much better practice/safer/more maintainable use 
static if
individually in any code that needs to treat characters and 
strings the same
way, since they are _not_ the same. Static typing exists for a 
reason.


More information about the Digitalmars-d mailing list