In this code example, the goal is to create a function that takes an std::array of a known type but an unknown size. This is a common scenario that can arise in various programming tasks.
<code class="cpp">// made up example void mulArray(std::array<int, ?>& arr, const int multiplier) { for(auto& e : arr) { e *= multiplier; } } // lets imagine these being full of numbers std::array<int, 17> arr1; std::array<int, 6> arr2; std::array<int, 95> arr3; mulArray(arr1, 3); mulArray(arr2, 5); mulArray(arr3, 2);</code>
However, during the developer's search for a solution, they encountered suggestions to use function templates. While function templates can solve this problem, they may introduce additional complexity and aren't always the most efficient approach.
The question posed is whether there's a simpler way to accomplish this task, similar to how one would work with plain C-style arrays. Unfortunately, the answer is negative. In C , there's no direct way to pass an array of unknown size to a function without using function templates.
To make it possible, one must indeed resort to function templates, as illustrated below:
<code class="cpp">template<std::size_t SIZE> void mulArray(std::array<int, SIZE>& arr, const int multiplier) { for(auto& e : arr) { e *= multiplier; } }</code>
This function template can be used with arrays of any size, as demonstrated in the following live example: https://godbolt.org/z/sV49sK
The above is the detailed content of Can std::array with Unknown Size be Passed to a Function Directly?. For more information, please follow other related articles on the PHP Chinese website!