Checkpoint 23.6.1.
Define a templated struct
LabeledValue that holds a value of type T and a label of type string (in that order).
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;
};
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.)
Pair struct with different types:
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:
// 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);
}
LabeledValue that holds a value of type T and a label of type string (in that order).