Home > Backend Development > C++ > body text

Can std::array with Unknown Size be Passed to a Function Directly?

Susan Sarandon
Release: 2024-10-25 04:44:29
Original
293 people have browsed it

Can std::array with Unknown Size be Passed to a Function Directly?

Passing an std::array of Unknown Size to a Function

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>
Copy after login

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>
Copy after login

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!

source:php
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!