Passing Spans to Functions
Write flexible APIs.
One Function, Many Containers
A function taking std::span accepts arrays, vectors, and raw buffers alike, no templates or overloads needed.
#include <iostream>
#include <span>
#include <vector>
#include <array>
int sum(std::span<const int> s) {
int t = 0; for (int x : s) t += x; return t;
}
int main() {
std::vector<int> v = {1, 2, 3};
std::array<int, 2> a = {4, 5};
std::cout << sum(v) << " " << sum(a) << "\n";
}No Size Parameter Needed
Old C-style APIs pass a pointer plus a separate size. A span bundles both, eliminating mismatched-length bugs.
#include <iostream>
#include <span>
void printAll(std::span<const int> s) {
for (int x : s) std::cout << x << " ";
std::cout << "\n";
}
int main() {
int buf[] = {7, 8, 9};
printAll(buf); // size inferred
}All lessons in this course
- Fixed-Size std::array
- std::span Basics
- Passing Spans to Functions
- Bounds and Subspans