diff --git a/include/gsl/gsl_util b/include/gsl/gsl_util index d1f7f33..bc65923 100644 --- a/include/gsl/gsl_util +++ b/include/gsl/gsl_util @@ -96,6 +96,10 @@ constexpr T narrow_cast(U&& u) noexcept return static_cast(std::forward(u)); } +struct narrowing_error : public std::exception +{ +}; + namespace details { template @@ -115,9 +119,9 @@ constexpr T narrow(U u) noexcept(false) { T t = narrow_cast(u); - if (static_cast(t) != u) gsl::details::terminate(); + if (static_cast(t) != u) throw narrowing_error{}; if (!details::is_same_signedness::value && ((t < T{}) != (u < U{}))) - gsl::details::terminate(); + throw narrowing_error{}; return t; } diff --git a/tests/utils_tests.cpp b/tests/utils_tests.cpp index f7f7ce3..98faf58 100644 --- a/tests/utils_tests.cpp +++ b/tests/utils_tests.cpp @@ -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(n); EXPECT_TRUE(c == 120); @@ -123,14 +118,13 @@ TEST(utils_tests, narrow) EXPECT_TRUE(narrow(int32_t(1)) == 1); EXPECT_TRUE(narrow(int32_max) == static_cast(int32_max)); - EXPECT_DEATH(narrow(int32_t(-1)), deathstring); - EXPECT_DEATH(narrow(int32_min), deathstring); + EXPECT_THROW(narrow(int32_t(-1)), narrowing_error); + EXPECT_THROW(narrow(int32_min), narrowing_error); n = -42; - EXPECT_DEATH(narrow(n), deathstring); + EXPECT_THROW(narrow(n), narrowing_error); #if GSL_CONSTEXPR_NARROW static_assert(narrow(120) == 120, "Fix GSL_CONSTEXPR_NARROW"); #endif - }