On Thursday, February 02, 2012 13:18:17 bearophile wrote: > Alex R. Petersen: > > (Sorry for my last blank answer.) > > > Because D is a strongly typed language. Casting a string to an int > > doesn't make sense from a type system perspective. > > I think that D being strongly typed is not significant here. When you cast a > string to char* you are casting a 2 words struct to a single pointer, when > you cast a char* to long on a 32 bit system you are changing type and size, > etc. The purpose of cast() is right to break the strongly typed nature of > the D type system. > > So I think a better answer is that D designers have decided to give > different purposes to to!X(y) and cast(X)x. The cast() is meant to be a > light and very quick conversion, usually done at compile-time (unless it's > a dynamic cast), to throw no exceptions, and generally unsafe. to!() is > meant to be safer, to throw exceptions if the conversion fails, and it uses > library code, so it's more flexible, and often performs some work at > run-time too. Given such design a string->int conversion is better left to > to!().
Casts generally reintrepret what they're converting on some level (though not necessarily as exactly as C++'s reinterpret_cast does). The types involved are always similar and any converting that takes place is incredibly straightforward. They don't really convert in the sense of creating one type from another. It's closer to treating a type like another type than actually converting it. Strings are not at all similar to ints. One is an array. The other is a single integral value. So, it makes no sense to treat one like the other. std.conv.to, on the other hand, outright converts. It does what makes the most sense when trying to take a value of one type and create a value of another type from it. The two types may have absolutely nothing to do with each other. It's closer to constructing a value of one type from a value of another type than treating one like the other. So, as Bearophile says, the purposes of casting and std.conv.to are very different. - Jonathan M Davis