Hayashi Yoshiaki
Hayashi Yoshiaki

Reputation: 217

function which takes a general array type

I want to make a function which takes an array-like type (eg. std::vector, std::array, C array, ...etc). The body of my function only requires that the argument have a subscript operator [] which returns a specific type. For example, suppose I want to write following functions, Is there a way to write the code only once rather than repeating the same code three times?

AddOne(std::array<double> &array, int size){
  for(int i=0;i<size;i++){
  array[i] += 1;
}
AddOne(std::vector<double> &array, int size){
  for(int i=0;i<size;i++){
  array[i] += 1;
}
AddOne(double *array, int size){
  for(int i=0;i<size;i++){
  array[i] += 1;
}

Thanks in advance!

Upvotes: 2

Views: 57

Answers (1)

Thomas
Thomas

Reputation: 182028

Yep, this is what templates are for:

template<typename T>
AddOne(T &array, int size){
  for(int i=0;i<size;i++) {
    array[i] += 1;
  }
}

Note that you don't need to specify explicitly that the type needs to have an [] operator. This will be checked at every point where the template is being used (which can result in the unreadable compile errors that C++ is notorious for).


A more idiomatic approach would be to pass a pair of iterators:

template<typename T>
AddOne(T begin, T end) {
  for (; begin != end; begin++) {
    (*begin) += 1;
  }
}

For e.g. std::vector, you'd call AddOne(my_vector.begin(), my_vector.end()). For raw arrays, you'd just pass pointers, like AddOne(my_array, my_array + size).

Upvotes: 3

Related Questions