Why I could not cast string to int?
bearophile
bearophileHUGS at lycos.com
Thu Feb 2 10:18:17 PST 2012
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!().
Bye,
bearophile
More information about the Digitalmars-d-learn
mailing list