[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]
[lmi-commits] [lmi] master 28d7b307 1/4: Assert a necessary precondition
From: |
Greg Chicares |
Subject: |
[lmi-commits] [lmi] master 28d7b307 1/4: Assert a necessary precondition |
Date: |
Sun, 29 May 2022 20:51:23 -0400 (EDT) |
branch: master
commit 28d7b307b5466a9105503e009d32e763f8878ce1
Author: Gregory W. Chicares <gchicares@sbcglobal.net>
Commit: Gregory W. Chicares <gchicares@sbcglobal.net>
Assert a necessary precondition
This may seem plausible:
double e1 = nonstd::power
(static_cast<double>(double_traits::radix)
,static_cast<double>(double_traits::digits)
);
but it doesn't compile:
invalid 'double' operand to binary '&'
Added a static assertion that type 'Integral' is integral.
Noted that the code really assumes that type 'Integral' is not merely
integral, but also unsigned.
---
stl_extensions.hpp | 7 ++++++-
1 file changed, 6 insertions(+), 1 deletion(-)
diff --git a/stl_extensions.hpp b/stl_extensions.hpp
index f46d66d5..813820f7 100644
--- a/stl_extensions.hpp
+++ b/stl_extensions.hpp
@@ -55,6 +55,7 @@
#include <functional> // multiplies, plus
#include <stdexcept> // logic_error
+#include <type_traits> // is_integral_v
namespace nonstd
{
@@ -78,11 +79,15 @@ template <typename T> inline T
identity_element(std::multiplies<T>)
/// necessarily commutative.
///
/// GWC modification: throw on negative exponent--otherwise, the loop
-/// appears not to terminate.
+/// may never terminate, because the bitwise operators don't work as
+/// intended with negative values. Alternative not used: assert that
+/// type Integer is unsigned, as the author evidently assumed--but
+/// imposing that requirement now breaks too much existing lmi code.
template <typename T, typename Integer, typename MonoidOperation>
T power(T x, Integer n, MonoidOperation opr)
{
+ static_assert(std::is_integral_v<Integer>);
if(n < 0)
{
throw std::logic_error("power() called with negative exponent.");