-2

I'm trying to write a function that checks if the variable being cast can fit in the destination type, and assert() if not. Right now this is what I came up with. I didn't test it yet. I would like to make the template figure out the type of the varible being passed automatically, with something like typeid, although I don't really know what typeid really is. Is that possible? Also, I don't know much about templates.

template<typename from_T, typename to_T>
static inline to_T safe_cast(from_T variable)
{
    assert(variable >= std::numeric_limits<to_T>::min());
    assert(variable <= std::numeric_limits<to_T>::max());

    return static_cast<to_T>(variable);
}

Well, if that is actually some function that already does this that I don't know of I will be glad to hear.

1 Answers1

1

C++ Core Guidelines already has a gsl::narrow

// narrow() : a checked version of narrow_cast() that throws if the cast changed the value

You can see the Microsoft implementation here

// narrow() : a checked version of narrow_cast() that throws if the cast changed the value
template <class T, class U>
    constexpr T narrow(U u) noexcept(false)
{
    constexpr const bool is_different_signedness =
        (std::is_signed<T>::value != std::is_signed<U>::value);

    const T t = narrow_cast<T>(u);

    if (static_cast<U>(t) != u || (is_different_signedness && ((t < T{}) != (u < U{}))))
    {
        throw narrowing_error{};
    }

    return t;
}

You can see the explanation of the implementation on this SO post (it's for an older version of the implementation, but nothing substantially changed, so the answer still applies).

bolov
  • 72,283
  • 15
  • 145
  • 224