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:
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:
Of course, any function that was going to work on
Pair
s would need to be templated as well so that it can handle any type of Pair
. For example, a function to compare two Pair
s might look like:
// 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.