This sample is licensed under the CC0 Public Domain Dedication.
Pass fixed-size arrays to and from functions.
Built-in array types are not copyable, so cannot be passed to and from functions by value. The traditional approach is to pass both a pointer to an array’s first element and the size of the array. However, C++ provides class types that represent copyable fixed-size arrays.
We define the function
compile_time, on lines 4–5, to have a
parameter of type
std::array, which represents
compile-time fixed-size arrays. This means that the size must be
known at compile time. A template may be used to instantiate
functions for different
std::array sizes. Lines 12–14 demonstrate
passing arrays of size 3 to this function.
On lines 7–8, we define function
run_time to have a parameter of type
represents run-time fixed-size arrays. This type can be created with
any size at run time, but cannot change size once created. Lines 16–18
demonstrate passing arrays of various sizes to this function.
std::experimental::dynarray is part of the Arrays
Technical Specification, which provides experimental features that
may soon be introduced to the C++ standard. It should not be used
in production code.