0

Say that we have the following:

template <class T, int i>

I understand that T will be whatever type being passed to some function. But, what does the int i portion mean?

Thanks.

2 Answers2

2

One of the most common use cases for this kind of template class syntax is to provide some fixed size number of T's to handle:

template<typename T, size_t N>
class MyClass {
    std::array<T,N> theHandledInstancesOfT;
};

MyClass<int,42> my42IntegersManagedByMyClass;    

See also the std::array<> documentation for instance.

πάντα ῥεῖ
  • 1
  • 13
  • 116
  • 190
0

Let's compare two functions, one with a template and one without:

int add_two(int x, int y) {
    return (x + y);
}
// add_two(3, 4) == 7

template <int x, int y>
int add_two_2() {
    return (x + y);
}
// add_two_2<3, 4>() == 7

In the templatized version, the values of x and y are known already at compile time. This means that the compiler can, for instance, see that x = 3 and y = 4 means the result is 7, and just replace the entire function call with 7. In the first function, however, something like this is not possible, since the compiler doesn't know the values of x and y until the program is actually run.

Frxstrem
  • 38,761
  • 9
  • 79
  • 119