0Pricing
C++ Academy · Lesson

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

  1. Fixed-Size std::array
  2. std::span Basics
  3. Passing Spans to Functions
  4. Bounds and Subspans
← Back to C++ Academy