Skip to content

Instantly share code, notes, and snippets.

@michaelbartnett
Last active October 21, 2018 00:42
Show Gist options
  • Save michaelbartnett/0d28652587561fe87d51be54619c9217 to your computer and use it in GitHub Desktop.
Save michaelbartnett/0d28652587561fe87d51be54619c9217 to your computer and use it in GitHub Desktop.
#include <type_traits>
#include <assert>
// debug = gsl::narrow, release = gsl::narrow_cast
namespace util
{
template <class T, class U>
constexpr T narrowcast(U&& u) noexcept
{
static_assert(std::is_integral<T>::value, "T must be an integral type");
static_assert(!std::is_same<T, bool>::value, "T must not be a bool");
static_assert(std::is_integral<U>::value, "U must be an integral type");
static_assert(!std::is_same<U, bool>::value, "U must not be a bool");
assert(static_cast<U>(static_cast<T>(u)) != u);
assert((!details::is_same_signedness<T, U>::value && ((static_cast<U>(static_cast<T>(u)) < T{}) != (u < U{}))));
return static_cast<T>(std::forward(u));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment