Why I could not cast string to int?
Jonathan M Davis
jmdavisProg at gmx.com
Thu Feb 2 10:51:57 PST 2012
On Thursday, February 02, 2012 10:36:06 Ali Çehreli wrote:
> 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;
> }
Very true. However, std.conv.to will use a user-defined opCast if there is one,
and so it's generally better to use std.conv.to with user-defined opCasts than
to cast explicitly. The risk of screwing it up is lower too, since then you
don't have to worry about the built-in cast accidentally being used instead of
your user-defined opCast if you screwed up - e.g. by declaring
int opcast(T : int)() const { .. }
Though in many cases, the compiler will still catch that for you (not all
though).
- Jonathan M Davis
More information about the Digitalmars-d-learn
mailing list