Template Parameters

Templates can have more than one type parameter, allowing you to create more flexible and powerful templates. This is especially useful for creating generic data structures and algorithms.

Different Types of Template Parameters:

template <typename T, typename U>
class Pair {
    T first;
    U second;
public:
    Pair(T a, U b) : first(a), second(b) {}
    T getFirst() { return first; }
    U getSecond() { return second; }
};

int main() {
    Pair<int, string> myPair(1, "Hello");
    cout << myPair.getFirst();      // Output: 1
    cout << myPair.getSecond();     // Output: Hello
}

In this example:

  • template <typename T, typename U> declares a template with two type parameters.
  • class Pair holds a pair of values of types T and U.

Non-Type Template Parameters

Templates can also have non-type parameters, which are constants that are passed to the template. This feature is useful for creating arrays of fixed sizes or other compile-time constants.

What are Non-Type Template Parameters?

template <typename T, int size>
class Array {
    T arr[size];
public:
    int getSize() { return size; }
};

int main() {
    Array<int, 10> intArray;
    cout << intArray.getSize();     // Output: 10
}

In this example:

  • template <typename T, int size> declares a template with a type parameter and a non-type parameter.
  • class Array uses the non-type parameter size to define the size of the array.