On Thursday, 25 June 2015 at 03:40:31 UTC, Adam D. Ruppe wrote:
(An interesting point here though is since alias this DOES return a string, any duck-type checks or implicit conversion checks will also pass what it passes... and work, it'll just silently allocate the string. Which is no regression! The status quo is it allocates that string EVERY time anyway. But it also isn't ideal.

That depends entirely on what the templated function that it's being used with does. In general, implicit conversions in generic code is an incredibly bad idea. Almost inevitably what happens is that folks assume that because the type is implicitly convertible, it can be treated like the type that it implicitly converts to - but that often isn't true at all. It just means that you can convert it to that type and then use it as that type rather than its original type. So, if a function checks for implicit conversion and then forces that conversion, then it can work, but it needs to force the conversion. Otherwise, it'll either fail to compile when used with types that use alias this, or you'll end up with weird, hybrid behavior where some of the operations might use the actual type, whereas others use the converted type. In general, I think that using implicit conversions in generic code is a disaster.

So, yes, if we use a struct like this, then in code which ends up assigning the result to a string (or passing it to a function which explicitly takes a string), then the implicit conversion will take place, and everything should work fine. However, in any code that assumes that it's dealing with strings but doesn't actually use the type string anywhere, it's not going to implicitly convert to string, and you could easily end up with templated functions which test with isSomeString or similar and thus fail to compile, because they wouldn't do the implicit conversion in that case (the duck typing sees that the struct _isn't_ a string). As long as the functions work with general ranges of dchar, they should be fine (possibly less performant if too much autodecoding is going on, but the lack of allocation may make up for that), but any generic code that assumes strings without specifically using the type string is in trouble. How much of a concern that really is, I don't know. But I would not expect much code that involves duck typing to be converting the struct to string, and in general, I would be very worried about any generic code that involved implicit conversions.

But this should work just fine when used with non-generic code that's operating on strings or with generic code that operates on ranges of dchar and not necessarily just strings.

- Jonathan M Davis

Reply via email to