← 模式
传递数组
12345678910111213141516171819 | #include <array> #include <experimental/dynarray> void compile_time(std::array<int, 3> arr) { } void run_time(std::experimental::dynarray<int> arr) { } int main() { std::array<int, 3> arr = {4, 8, 15}; compile_time(arr); compile_time({16, 23, 42}); std::experimental::dynarray<int> dynarr = {1, 2, 3}; run_time(dynarr); run_time({1, 2, 3, 4, 5}); } |
此模式采用 CC0 公共领域贡献 许可。
需要 c++11 或更新版本。
意图
向函数传入和传出固定大小的数组。
描述
内置的数组类型不可复制,因此不能通过值传递给函数或从函数传出。传统的方法是同时传递一个指向数组首元素的指针和数组的大小。然而,C++ 提供了表示可复制的固定大小数组的类类型。
我们在第 4-5 行定义了函数 compile_time
,其参数类型为 std::array
,它表示编译时固定大小的数组。这意味着数组的大小必须在编译时确定。可以使用模板来为不同大小的 std::array
实例化函数。第 12-14 行演示了向该函数传递大小为 3 的数组。
在第 7-8 行,我们定义了函数 run_time
,其参数类型为 std::experimental::dynarray
,它表示运行时固定大小的数组。这种类型可以在运行时以任何大小创建,但一旦创建,大小就不能改变。第 16-18 行演示了向该函数传递不同大小的数组。
注意:std::experimental::dynarray
是数组技术规范 (Arrays Technical Specification) 的一部分,该规范提供了一些实验性特性,可能很快会引入 C++ 标准。它不应该在生产代码中使用。