0

I need to create a function to calculate the average of int types. how to do it better?

Example:

   double calculate_average(int num1, ...) {
      .... 
      return sum / count;
   }

   int main() {
     calculate_average(5, 4, 3, 2, 1);
     calculate_average(3, 2); 
   }
Weezyg
  • 25
  • 4
  • 3
    The term is "variadic function". But you'd probably be better off just passing a container of values, such as a `std::vector`. – Fred Larson May 21 '20 at 13:45
  • https://en.cppreference.com/w/cpp/utility/variadic , https://en.cppreference.com/w/cpp/language/variable_template , see also https://en.cppreference.com/w/cpp/algorithm/accumulate – Jesper Juhl May 21 '20 at 13:46
  • 3
    *"how to do it better?"* pass a `std::vector const&` for example, this will save many of the headaches that come with dealing with variadic templates. – Cory Kramer May 21 '20 at 13:46
  • @CoryKramer, vector doesn’t suit me, in my case – Weezyg May 21 '20 at 13:50
  • 2
    Could you elaborate why that is? – Cory Kramer May 21 '20 at 13:51
  • @CoryKramer, because we will know that the function already takes at least 1 argument - the vector – Weezyg May 21 '20 at 13:54

1 Answers1

3

You can use fold expressions for this:

template<typename ...Ts>
double calculate_average(Ts... ts)
{
  return (((double)ts / sizeof...(ts)) + ... + 0);
}

Note the sizeof...(ts), is a separate primitive for parameter packs. It's not a pack expansion, but instead gives the number of arguments that are passed into the function.

Here's a demo.

cigien
  • 57,834
  • 11
  • 73
  • 112