Tuesday, April 7, 2015

Overview

In C++, generics are done using templates. Templates generate the required code at compile time instead of at runtime. This improves performance significantly. You can find more information about templates here.

Content

Before

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
class calc
{
  public:
      int multiply(int x, int y);
      int add(int x, int y);
};

int calc::multiply(int x, int y)
{
    return x*y;
}
int calc::add(int x, int y)
{
    return x+y;
}

After

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
template <typename T>
class calc
{
  public:
    T multiply(T x, T y);
    T add(T x, T y);
};

template <typename T>
T calc<T>::multiply(T x, T y)
{
  return x*y;
}

template <typename T>
T calc<T>::add(T x, T y)
{
  return x+y;
}

After Specialized

This code will be specific for integers.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
template <>
class calc<int>
{
  public:
    int multiply(int x, int y);
    int add(int x, int y);
}

template <>
int calc<int>::multiply(int x, int y)
{
  return x*y;
}

template <>
int calc<int>::add(int x, int y)
{
  return x+y;
}

Random Posts