dimanche 22 décembre 2019

C++ function design

I came across the following question in multiple occasions this year but I don't have a clear answer to it: say I want to design a function that accumulates or in general builds something. I would need to declare the initial accumulator value (or an empty object in general), the problem is that whether I should initialize this value or object inside the function arguments with default value or should I initialize this thing inside the function body?

An example would be the following piece of function that split an sequential container into N equal size pieces (precondition: the pieces are splittable). Is it a okay to write it in the following form

template <typename T, std::size_t N>
array<T, N> equal_split(const T& x, array<T, N> result = {}) {
  for (int i = 0; i < N; ++i)
    std::copy(begin(x) + i * size(x) / 3, begin(x) + (i + 1) * size(x) / 3, std::back_inserter(result[i]));
  return result;
}

or is it better to write it as

template <typename T, std::size_t N>
array<T, N> equal_split(const T& x) {
  array<T, N> result = {};
  for (int i = 0; i < N; ++i)
    std::copy(begin(x) + i * size(x) / 3, begin(x) + (i + 1) * size(x) / 3, std::back_inserter(result[i]));
  return result;
}

Aucun commentaire:

Enregistrer un commentaire