Passing std:array around
arrays, c++, c++03
Solution
template<typename T, size_t N>
void myFunc(std::array<T, N> const &p) {
cout << "array contains " << p.size() << "elements";
}
`std::array` is not a class and cannot be used like a class. It's a template, and you must instantiate the template in order to get a class that can be used like a class.
Also, the size is part of the type of an array. If you want a container where the size isn't part of the type then you can use something like `std::vector`. Alternatively you can write a template that works for any object that has the functionality you need:
template<typename Container>
void myFunc(Container const &p) {
cout << "Container contains " << p.size() << "elements";
}
Problem
I'm trying to write a function that will work on a std::array of variable size, eg: ``` std::array a<int,5>={1,2,3,4,5}; std::array b<int,3>={6,7,8}; myFunc(a); myFunc(b); void myFunc(std::array &p) { cout << "array contains " << p.size() << "elements"; } ``` However, it doesn't work unless I specify the size, but I want the function to get the size from the array. I really didn't want the copying and dynamic allocation that vector uses, I want to use the space allocated by std::array() and don't want the compiler creating a copy of the function for every possible size of array. I thought about creating a template that works like array but will take a pointer to existing data rather than allocating it itself, but don't want to reinvent the wheel. Is this possible somehow?