The OpenD Programming Language

castFrom

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

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.

template castFrom (
From
) {}

Members

Functions

to
auto ref to(T value)

Parameters

From

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

Examples

// 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);
}

Meta