I've been putting my nose in std.algorithm recently, specifically, requirements of algorithms.

I must say I'm a big fan of conditional implementations. Given the genericity of templates (!), it can be very hard to overload them correct without conditional implementation. It is a really useful language feature

That said, more often than not, they are also used to validate input. While this is a good thing, when a developer DOES try to call an algorithm with invalid input, he is greeted with the cryptic: "Error: template foo does not match any function template declaration"
Followed by the (potentially long) list of candidates.
More often than not, the conditional implementations are actually quite complicated, and contain up to 5 or 6 different conditions.

The worse part is that the developer has no idea _which_ condition he has violated.

This is a shame, since most of the time, the conditions are not necessary for disambiguation, and a static assert would work just as well, and be more verbose.

Simple example:
minPos doesn't shouldn't operate on infinite ranges. compare:
Range minPos(Range)(Range R1) if (is(inputRange!Range) && !isInfinite!Range) {...}
vs
Range minPos(Range)(Range R1) if (is(inputRange!Range)
{
static assert(!isInfinite!Range, "minPos cannot operate on infinite ranges.")
    ...
}

Now, if a developer ever accidentally calls minPos with an infinite range, he gets slapped in the face with a very explicit compilation warning. This (I think) is great, because the "isInfinite" test is really just an implementation detail.

inputRange is really the input condition of the range, and should stay conditional.

--------
How do you feel about "assertive input validation" vs "conditional implementation"?

Is this something you'd like to see more of in algorithm?

Reply via email to