Bookmark and Share
Generics and Functions - 2020





Sum of objects
C code

The following C code calculates the sum of each elements in an array:

#include <stdio.h>
int array_sum(int data[], int size)
{
  int i, sum = 0;
  for(i = 0; i < size; i++) sum += data[i];
  return sum;
}

int main()
{
  int i, d[] = {1, 2, 3, 4, 5};
  printf(" sum = %d\n", array_sum(d, sizeof(d)/sizeof(d[0])));
  return 0;
}

C++ code

C++ generic version to sum any type of objects:

#include <iostream>
using namespace std;

template <typename T>
T array_sum(const T data[], int sz, T s = 0.0)
{
  for(int i = 0; i < sz; i++) s += data[i];
  return s;
}

int main()
{
  int di[] = {1, 2, 3, 4, 5};
  double dd[] = {1.1, 2.2, 3.3, 4.4, 5.5};

  cout << "int sum = " << array_sum(di, sizeof(di)/sizeof(di[0])) << endl;
  cout << "double sum = " << array_sum(dd, sizeof(dd)/sizeof(dd[0])) << endl;

  return 0;
}


For more information about templates:

  1. Templates
  2. Template Specialization
  3. Template Specialization - Traits
  4. Template Implementation & Compiler (.h or .cpp?)