diff --git a/changelog/clamp_assert_message.dd b/changelog/clamp_assert_message.dd new file mode 100644 index 00000000000..abaf3929c49 --- /dev/null +++ b/changelog/clamp_assert_message.dd @@ -0,0 +1,8 @@ +Better static assert messages for `std.algorithm.comparison.clamp` + +Until now, `clamp` used a template constraint to check if the passed types +could be used. If they were not, it was very tedious to figure out why. + +As the template constraint is not used for overload resolution +the constrains are moved into static asserts with expressive error +messages. diff --git a/std/algorithm/comparison.d b/std/algorithm/comparison.d index 5ecb4f601a5..5c70960a711 100644 --- a/std/algorithm/comparison.d +++ b/std/algorithm/comparison.d @@ -577,19 +577,20 @@ Returns: and `T3` are different. */ T1 clamp(T1, T2, T3)(T1 val, T2 lower, T3 upper) -if (is(typeof(val.lessThan(lower) ? lower : val.greaterThan(upper) ? upper : val)) - && (is(T2 : T1) && is(T3 : T1))) -// cannot use : -// `if (is(typeof(val.lessThan(lower) ? lower : val.greaterThan(upper) ? upper : val) : T1)) -// because of https://issues.dlang.org/show_bug.cgi?id=16235. -// Once that is fixed, we can simply use the ternary in both the template constraint -// and the template body -in { + static assert(is(T2 : T1), "T2 of type '", T2.stringof + , "' must be implicitly convertible to type of T1 '" + , T1.stringof, "'"); + static assert(is(T3 : T1), "T3 of type '", T3.stringof + , "' must be implicitly convertible to type of T1 '" + , T1.stringof, "'"); + assert(!lower.greaterThan(upper), "Lower can't be greater than upper."); -} -do -{ + + // `if (is(typeof(val.lessThan(lower) ? lower : val.greaterThan(upper) ? upper : val) : T1)) + // because of https://issues.dlang.org/show_bug.cgi?id=16235. + // Once that is fixed, we can simply use the ternary in both the template constraint + // and the template body if (val.lessThan(lower)) return lower; else if (val.greaterThan(upper))