View source code
Display the source code in std/conv.d from which this page was generated on github.
Report a bug
If you spot a problem with this page, click here to create a Bugzilla issue.
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.

Template std.conv.castFrom

A wrapper on top of the built-in cast operator that allows one to restrict casting of the original type of the value.

template castFrom(From) ;

A common issue with using a raw cast is that it may silently continue to compile even if the value's type has changed during refactoring, which breaks the initial assumption about the cast.

Contained Functions

NameDescription
to

Parameters

NameDescription
From The type to cast from. The programmer must ensure it is legal to make this cast.

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

License

Boost License 1.0.