mirror of
https://github.com/microsoft/GSL.git
synced 2024-11-03 17:56:43 -05:00
Changed implementation of gsl::narrow to throw gsl::narrowing_error
Implementation now behaves as described in the C++ Core Guidlines
This commit is contained in:
parent
9f6a9a5807
commit
61534ca3ad
@ -96,6 +96,10 @@ constexpr T narrow_cast(U&& u) noexcept
|
||||
return static_cast<T>(std::forward<U>(u));
|
||||
}
|
||||
|
||||
struct narrowing_error : public std::exception
|
||||
{
|
||||
};
|
||||
|
||||
namespace details
|
||||
{
|
||||
template <class T, class U>
|
||||
@ -115,9 +119,9 @@ constexpr
|
||||
T narrow(U u) noexcept(false)
|
||||
{
|
||||
T t = narrow_cast<T>(u);
|
||||
if (static_cast<U>(t) != u) gsl::details::terminate();
|
||||
if (static_cast<U>(t) != u) throw narrowing_error{};
|
||||
if (!details::is_same_signedness<T, U>::value && ((t < T{}) != (u < U{})))
|
||||
gsl::details::terminate();
|
||||
throw narrowing_error{};
|
||||
return t;
|
||||
}
|
||||
|
||||
|
@ -104,11 +104,6 @@ TEST(utils_tests, narrow_cast)
|
||||
|
||||
TEST(utils_tests, narrow)
|
||||
{
|
||||
std::set_terminate([] {
|
||||
std::cerr << "Expected Death. narrow";
|
||||
std::abort();
|
||||
});
|
||||
|
||||
int n = 120;
|
||||
const char c = narrow<char>(n);
|
||||
EXPECT_TRUE(c == 120);
|
||||
@ -123,14 +118,13 @@ TEST(utils_tests, narrow)
|
||||
EXPECT_TRUE(narrow<uint32_t>(int32_t(1)) == 1);
|
||||
EXPECT_TRUE(narrow<uint32_t>(int32_max) == static_cast<uint32_t>(int32_max));
|
||||
|
||||
EXPECT_DEATH(narrow<uint32_t>(int32_t(-1)), deathstring);
|
||||
EXPECT_DEATH(narrow<uint32_t>(int32_min), deathstring);
|
||||
EXPECT_THROW(narrow<uint32_t>(int32_t(-1)), narrowing_error);
|
||||
EXPECT_THROW(narrow<uint32_t>(int32_min), narrowing_error);
|
||||
|
||||
n = -42;
|
||||
EXPECT_DEATH(narrow<unsigned>(n), deathstring);
|
||||
EXPECT_THROW(narrow<unsigned>(n), narrowing_error);
|
||||
|
||||
#if GSL_CONSTEXPR_NARROW
|
||||
static_assert(narrow<char>(120) == 120, "Fix GSL_CONSTEXPR_NARROW");
|
||||
#endif
|
||||
|
||||
}
|
||||
|
Loading…
Reference in New Issue
Block a user