Namespaces
Variants

std::define_static_array

From cppreference.com
< cpp | meta
Defined in header <meta>
template< ranges::input_range R >
consteval std::span<const ranges::range_value_t<R>> define_static_array( R&& r );
(since C++26)

Promotes array to static storage.

Let N be static_cast<std::size_t>(ranges::size(r)) if ranges::size(r) is a constant expression, or std::dynamic_extent otherwise. The effect is equivalent to:

using T = ranges::range_value_t<R>;
std::meta::info array = std::meta::reflect_constant_array(r);
if (std::meta::is_array_type(std::meta::type_of(array)))
    return std::span<const T, N>(std::meta::extract<const T*>(array),
                                 std::meta::extent(std::meta::type_of(array)));
else
    return std::span<const T, N>(static_cast<const T*>(nullptr), 0);

Parameters

r - an input_range whose elements are copy-constructible and have structural type

Return value

If the size of r is not zero, a span constructed from an array of type const T[N] (where T is ranges::range_value_t<R> and N is the size of r). Each element of the array is initialized from the value or object represented by std::meta::reflect_constant(static_cast<T>(*it)), where it is an iterator to the corresponding element of r.

Otherwise (the size of r is zero), an empty span.

Notes

As a template parameter object, the resulting array object (if present) has static storage duration. Ranges with template-argument-equivalent contents correspond to the same array object.

The array object is a potentially non-unique object.

Example

Compiler-explorer link.

#include <algorithm>
#include <meta>
#include <print>
#include <vector>

constexpr std::vector<double> precompute_angles(std::size_t size)
{
    std::vector<double> angles(size);
    for (int i{}; double& angle : angles)
        angle = 360.0 / size * i++;
    
    return angles;
}

consteval std::span<const double> precompute_angles_arr(std::size_t size)
{
    std::vector<double> angles = precompute_angles(size);
    return std::define_static_array(angles);
}

int main()
{
    // std::vector<double> angles = precompute_angles(7);
    //     error: call to consteval function ‘precompute_angles(7)’ is not a constant
    //            expression because it refers to a result of ‘operator new’

    std::span<const double> angles = precompute_angles_arr(7);
    for (double angle : angles)
        std::print("{:.1f} ", angle);

    std::println();
}

Output:

0.0 51.4 102.9 154.3 205.7 257.1 308.6

See also

promotes compile-time string to static storage, returning a pointer to the first character of the static string
(function template) [edit]
promotes compile-time value into static storage, returning a pointer to the static object
(function template) [edit]
promotes compile-time array into static storage, returning a reflection representing the static array
(function template) [edit]