Reputation: 45
I know there are some questions out there with this topic, but no one answered my question so far. I have seen that it is a bit complicated to define a function that takes an std::array of any length.
Is the example below the only way (excluding passing the length as an extra parameter) to do this?
template <typename T, size_t N>
void addstdArray(std::array<T, N> &arr) {
for(int i : arr) {
arr[i]++;
}
}
Upvotes: 0
Views: 32
Reputation: 66200
- Is the example below really the only way (excluding passing the length as an extra parameter) to do this?
No.
A possible alternative is the following
template <typename T>
void addstdArray (T & arr) {
// ...
}
This way you match almost everithing, non only standard arrays of every dimension
- If so, is it a good practice?
Depends from your needs but, generally speaking, I don's see contraindications.
- I have heard that one should avoid templates if possible (regarding debugging etc.). Is it better to solve the whole thing with std::vector then? The access times should not differ that much, should they?
The standard C++ (and standard libraries) is heavily based on templates.
std::vector
is another example of extremely useful standard template class.
std::array
could be better or worse, according to your needs.
No: I don't think is better avoid templates.
Upvotes: 2