In C++11, how would I go about writing a function (or method) that takes a std::array of known type but unknown size?
// 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);
During my search I only found suggestions to use templates, but those seems messy (method definitions in header) and excessive for what I'm trying to accomplish.
Is there a simple way to make this work, as one would with plain C-style arrays?
Is there a simple way to make this work, as one would with plain C-style arrays?
No. You really cannot do that unless you make your function a function template (or use another sort of container, like an std::vector
, as suggested in the comments to the question):
template<std::size_t SIZE>
void mulArray(std::array<int, SIZE>& arr, const int multiplier) {
for(auto& e : arr) {
e *= multiplier;
}
}
Here is a live example.