View source code
Display the source code in std/conv.d from which this page was generated on
github.
Improve this page
Quickly fork, edit online, and submit a pull request for this page.
Requires a signed-in GitHub account. This works well for small changes.
If you'd like to make larger changes you may want to consider using
local clone.
Page wiki
View or edit the community-maintained wiki page associated with this page.
Function std.conv.castFrom.to
Prototype
ref auto to(To, T)( T value ) @system;
Parameters
| Name | Description |
|---|---|
| To | The type to cast to. |
| value | The value to cast. It must be of type From,
otherwise a compile-time error is emitted. |
Returns
the value after the cast, returned by reference if possible.
Example
// Regular cast, which has been verified to be legal by the programmer:
{
long x;
auto y = cast(int) x;
}
// However this will still compile if 'x' is changed to be a pointer:
{
long* x;
auto y = cast(int) x;
}
// castFrom provides a more reliable alternative to casting:
{
long x;
auto y = castFrom!long.to!int(x);
}
// Changing the type of 'x' will now issue a compiler error,
// allowing bad casts to be caught before it's too late:
{
long* x;
static assert (
!__traits(compiles, castFrom!long.to!int(x))
);
// if cast is still needed, must be changed to:
auto y = castFrom!(long*).to!int(x);
}
}
Authors
Walter Bright, Andrei Alexandrescu, Shin Fujishiro, Adam D. Ruppe, Kenji Hara