Range Kind Templates

Get introduced to the range kind templates.

We'll cover the following

We used mostly int ranges in the previous chapter. In practice, containers, algorithms, and ranges are almost always implemented as templates. The print() example was a template as well:

void print(T)(T range) {
    // ...

What lacks from the implementation of print() is that even though it requires T to be a kind of InputRange, it does not formalize that requirement with a template constraint.

The std.range module contains templates that are useful both in template constraints and in static if statements.

Range kind templates

The group of templates with names starting with is determine whether a type satisfies the requirements of a certain kind of range. For example, isInputRange!T answers the question “is T an InputRange?”. The following templates are for determining whether a type is of a specific general range kind:

  • isInputRange

  • isForwardRange

  • isBidirectionalRange

  • isRandomAccessRange

  • isOutputRange

Accordingly, the template constraint of print() can use isInputRange:

void print(T)(T range)
        if (isInputRange!T) {
    // ...

Unlike the others, isOutputRange takes two template parameters: (i) a range type and (ii) an element type. It returns true if the range type allows outputting that element type. For example, the following constraint requires that the range must be an OutputRange that accepts double elements:

void foo(T)(T range)
        if (isOutputRange!(T, double)) {
    // ...

When used in conjunction with static if, these constraints can also determine the capabilities of user-defined ranges. For example, when a dependent range of a user-defined range is a ForwardRange, the user-defined range can take advantage of that fact and can provide the save() function as well.

Let’s see this on a range that produces the negatives of the elements of an existing range (more accurately, the numeric complements of the elements). Let’s start with just the InputRange functions:

Get hands-on with 1000+ tech skills courses.