Why I could not cast string to int?

xancorreu xancorreu at gmail.com
Thu Feb 2 11:00:34 PST 2012


Al 02/02/12 19:18, En/na bearophile ha escrit:
> 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
Okay, very useful answer!
Can I say "serialize the first, second and third arguments as Class Person"?

I mean, if you define a class Person like:

class Person {
     string name
     uint age
     dead bool
}

could you serialize the input from console, like 
Std.in.serialize(Person, args(0), args(1), args(2))?

You could do that "manually" checking each paramm, but it's a tedious task.
Thanks,
Xan.


More information about the Digitalmars-d-learn mailing list