Last active
October 21, 2018 00:42
-
-
Save michaelbartnett/0d28652587561fe87d51be54619c9217 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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