Slicing Operators

Let’s discuss slicing operators in this lesson.

We'll cover the following

Use of slicing operators

opSlice allows slicing the objects of user-defined types with the [] operator.

In addition to this operator, there are also opSliceUnary, opSliceAssign, and opSliceOpAssign, but they are discouraged.

D supports multidimensional slicing. You will see a multidimensional example later in the templates chapter. Although the methods described in that chapter can be used for a single dimension as well, they do not match the indexing operators that are defined above and they involve templates that we have not covered yet. For that reason, we will see the non-templated use of opSlice in this chapter, which works only with a single dimension.

opSlice has two distinct forms:

  • The square brackets can be empty, as in deque[] to mean all elements.

  • The square brackets can contain a number range, as in deque[begin..end], to mean the elements in the specified range.

The slicing operators are relatively more complex than other operators because they involve two distinct concepts: container and range.

In single-dimensional slicing, which does not use templates, opSlice returns an object that represents a specific range of elements of the container. The object that opSlice returns is responsible for defining the operations that are applied on that range element. For example, behind the scenes, the following expression is executed by first calling opSlice to obtain a range object and then applying opOpAssign!"*" on that object:

deque[] *= 10; // multiply all elements by 10
// The equivalent of the above:
{
    auto range = deque.opSlice();
    range.opOpAssign!"*"(10); 
}

Accordingly, the opSlice operators of DoubleEndedQueue return a special Range object so that the operations are applied to it:

Get hands-on with 1200+ tech skills courses.