How it works...

In this recipe, we will explore what std::span is and why it is needed. In C++ (and even in C), to pass an array to a function, the following is implemented:

void foo(const int *array, size_t size){    for (auto i = 0; i < size; i++) {        std::cout << array[i] << ' ';    }    std::cout << '\n';}

As shown in the preceding example, we have created a function called foo() that takes a pointer to an array as well as the size of the array. We then use this information to output the contents of the array to stdout.

We can execute this function as follows:

int main(void){    int array[] = {4, 8, 15, 16, 23, 42};    foo(array, sizeof(array)/sizeof(array[0]));}

This results in the following output:

The problem with the preceding code is that it is ...

Get Advanced C++ Programming Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.