Why I could not cast string to int?
Ali Çehreli
acehreli at yahoo.com
Thu Feb 2 10:36:06 PST 2012
On 02/02/2012 10:18 AM, bearophile wrote:
> The cast() is meant to be a light and very quick conversion,
> usually done at compile-time (unless it's a dynamic cast),
I first read it as if you were saying that dynamic cast is the only one
that is done at runtime. Actually many casts are done at runtime even
for fundamental types.
> to throw no exceptions, and generally unsafe.
Just to be complete: You mean it for fundamental types. Of course user
types' opCast operators may throw:
import std.exception;
class C
{
int opCast(T : int)() const
{
enforce(false, "Not good.");
return 42;
}
}
void main()
{
auto c = new C;
auto i = cast(int)c;
}
> 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!().
Agreed.
>
> Bye,
> bearophile
Ali
More information about the Digitalmars-d-learn
mailing list