opCast'ing strings

bauss jj_1337 at live.dk
Mon Nov 13 12:40:39 UTC 2017


On Monday, 13 November 2017 at 01:12:59 UTC, Adam D. Ruppe wrote:
> On Monday, 13 November 2017 at 01:03:17 UTC, helxi wrote:
>> In this program, casting using to does not work as intended 
>> (returning 23/11) on the struct. However, calling opCast 
>> directly seems to do the job. Why is that?
>
>
> to!string calls a function called `string toString() {}` on the 
> struct, not the cast operator.

Which is generally what you want to use anyway and not a cast 
overload.

My rule of thumb (Which can of course differ per preference.) is 
that cast overload should only be done between the following:

struct <-> scalar types
class <-> scalar types
struct <-> class

Any string conversions should always be done with `toString()`.

Anything else should not be implemented with casts or conversion 
methods. An exception of course is creating slices, which is 
acceptable using `opSlice`, but generally I avoid using something 
like `opCast` to an array, UNLESS it's an array wrapper, which 
you most likely won't have in D anyway, because you'd be better 
off creating a range.






More information about the Digitalmars-d-learn mailing list