Template overloads involving `string` and `char[constant]` return value

Adam D. Ruppe via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Wed Sep 21 05:20:14 PDT 2016


On Wednesday, 21 September 2016 at 12:07:31 UTC, Johan Engelen 
wrote:
>     string a = toHexString(hash);

This is a pretty common pitfall (and IMO one of the most 
egregious design flaws in the language), I see it all the time.

toHexString, when given a static array, returns a static array, 
but the language allows you to implicitly slice that into a 
pointer (mistaken design in any case, doubly so since it a stack 
pointer)... and moreover it is implicitly cast to immutable!

So it will implicitly cast that char[x] to string in a LOT of 
places... and it is almost always wrong.

If you passed `hash[]` it should then do what you want... so 
arguably the implicit slice rule is confusing you here too, I'd 
LOVE to kill that rule entirely.

> I don't know whether this is a compiler bug (choosing the wrong 
> overload) or a Phobos bug (overloads don't work like that).

It is neither, the compiler chose the right overload (remember, 
overloads are chosen based on the arguments alone, the type you 
specify for the variable holding the return value isn't a 
consideration there) and the implementation of each overload is 
correct.

But the horribly wrong implicit slice and cast rules make it do 
the totally wrong thing while looking fine at first glance.


More information about the Digitalmars-d-learn mailing list