std::dynamic_extent

< cpp‎ | container‎ | span
定义于头文件 <span>
inline constexpr std::size_t dynamic_extent = std::numeric_limits<std::size_t>::max();
(C++20 起)

std::dynamic_extentstd::size_t 类型常量,用于区别拥有静态和动态长度的 std::span

注解

由于 std::size_t 是无符号类型,等价的定义是:

inline constexpr std::size_t dynamic_extent = -1;

整型转换

示例

#include <array>
#include <cassert>
#include <cstddef>
#include <iostream>
#include <span>
#include <string_view>
#include <vector>
 
int main()
{
    auto print = [](std::string_view const name, std::size_t ex) {
        std::cout << name << ", ";
        if (ex == std::dynamic_extent) {
            std::cout << "dynamic extent\n";
        } else {
            std::cout << "static extent = " << ex << '\n';
        }
    };
 
    int a[]{1,2,3,4,5};
 
    std::span span1{a};
    print("span1", span1.extent);
 
    std::span<int, std::dynamic_extent> span2{a};
    print("span2", span2.extent);
 
    std::array ar{1,2,3,4,5};
    std::span span3{ar};
    print("span3", span3.extent);
 
    std::vector v{1,2,3,4,5};
    std::span span4{v};
    print("span4", span4.extent);
}

输出:

span1, static extent = 5
span2, dynamic extent
span3, static extent = 5
span4, dynamic extent

参阅

(C++20)
对象的连续序列上的无所有权视图
(类模板)