Using template constraints and static if
We saw template constraints and static if
used in our range consuming functions in Chapter 3, Ranges. There, they were used to selectively use range functionality for the purpose of optimization and explicitly documenting our interface requirements. These same features can also be used for producing custom compile-time errors.
Getting ready
To understand the problem we're trying to solve, compile the following simple program:
void main() { import std.conv; struct Foo {} Foo f; int i = to!int(f); }
Also, observe the long error message with most of the locations being reported as inside Phobos! (If you look at the very last line of the message, it will finally report the location in your code.) It also doesn't tell you why it didn't match.
Similarly, try to call std.algorithm.sort
with a range that lacks one of the requirements. It may fail to provide swappable or assignable elements or might have a typo in a property name like emptty
instead...