Skip to main content

Section 23.6 Templated Data Types

In addition to writing templated functions, we can also write templated data typesβ€”structs or objects whose members can be of any type. For example, we might want to be able to group two pieces of data into a β€œpair”. Rather than write a struct IntPair that only works with integers, or a DoublePair that only works with doubles, we can write a templated struct:
Listing 23.6.1.
template<typename T>
struct Pair {
    T first;
    T second;
};
This definition says that a Pair<T> has two member variables of type T. To use this templated data type, we generally must specify the type when declaring a variable of that type. Pair<int> for a pair of ints, Pair<double> for a pair of doubles, and so on. (The compiler may be able to guess the type in some cases, meaning that in those cases we could just write Pair, but it is best to always be explicit.)
The program below demonstrates using our Pair struct with different types:
Listing 23.6.2.
Of course, any function that was going to work on Pairs would need to be templated as well so that it can handle any type of Pair. For example, a function to compare two Pairs might look like:
Listing 23.6.3.
// Two pairs, both of type T, are equal if their first and second elements are equal
template<typename T>
bool areEqual(const Pair<T>& p1, const Pair<T>& p2) {
    return (p1.first == p2.first) && (p1.second == p2.second);
}
You have attempted of activities on this page.