dwto
dwto

Reputation: 805

Why extent of std::span created from a static array considered to have a dynamic_extent?

Why is the following static array considered to have a dynamic extent?

#include <iostream>
#include <span>
     
int main()
{
    char static_array[]={1,2,3};
    std::span<char> sp{static_array};
    if (std::dynamic_extent == sp.extent)
        std::cout << "Why dynamic?" << std::endl;
}

This prints: "Why dynamic?" so this is clearly not how it is supposed to be used. What am I missing?

Upvotes: 5

Views: 126

Answers (1)

Ted Lyngmo
Ted Lyngmo

Reputation: 117812

The std::span extent is dynamic by default even though the owning array's extent is not.

If you want it to have a static extent, specify it upon construction:

std::span<char, std::size(static_array)> sp{static_array};
//              ^^^^^^^^^^^^^^^^^^^^^^^

Or just don't specify any template parameters to let them be deduced:

std::span sp{static_array};

In the latter case, the below deduction guide will make the extent static:

template< class T, std::size_t N >
span( T (&)[N] ) -> span<T, N>;

Upvotes: 10

Related Questions