himbeerHummus
himbeerHummus

Reputation: 45

Passing std::array

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?

  1. Is the example below really the only way (excluding passing the length as an extra parameter) to do this?
  2. If so, is it a good practice?
  3. 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?
template <typename T, size_t N>
void addstdArray(std::array<T, N> &arr) {

    for(int i : arr) {
        arr[i]++;
    }
}

Upvotes: 0

Views: 32

Answers (1)

max66
max66

Reputation: 66200

  1. 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

  1. If so, is it a good practice?

Depends from your needs but, generally speaking, I don's see contraindications.

  1. 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

Related Questions